i'm tryng make a regex to get the string between some number and underscore, for example:
I have CP_01Ags_v5, so I need a regex to match just Ags
. another example could be CP_13Hgo_v5 and match Hgo
.
Some idea?
i'm tryng make a regex to get the string between some number and underscore, for example:
I have CP_01Ags_v5, so I need a regex to match just Ags
. another example could be CP_13Hgo_v5 and match Hgo
.
Some idea?
Based off the examples and matches you are describing. You want something along the lines of.
[0-9]+(.*)[_]
to break it down. The regex looking for any number that shows up one or more times then matches everything after the number(s) up until the [_] underscore.
The downfall is this assumes the examples you provided are similar. If your example is
CP_13Hgo_v5asdf_
then it will match
Hgo_v5asdf
if you have other possible findings then you want the non-greedy version of this regex.
[0-9]+(.*?)[_]
this will cause two groups to be found in this example
CP_13Hgo_v5asdf_
will find the following groups:
Hgo
and
asdf
You can use look-arounds to match just the string between the digits and the underscore e.g.
(?<=\d)[A-Za-z]+(?=_)
In C# (note the need to escape the \
in the regex):
String s = @"CP_01Ags_v5 CP_13Hgo_v5";
Match m = Regex.Match(s, "(?<=\\d)[A-Za-z]+(?=_)");
while (m.Success) {
Console.WriteLine(m.Value);
m = m.NextMatch();
}
Output
Ags
Hgo
If your string is always at least two characters and there are no other strings of at least two characters, then you can apply the following:
var text = "CP_01Ags_v5";
var x = Regex.Match(text, @"(?<!^)[A-Za-z]{2,}");
Use Regex Group
:
(?<leftPart>_\d{2})(?<YourTarget>[a-zA-Z])(?<rightPart>_[a-zA-Z0-9]{2})
C#
:
Regex re = new Regex(@"(?<leftPart>_\d{2})(?<YourTarget>[a-zA-Z])(?<rightPart>_[a-zA-Z0-9]{2})");
/*
* Loop
* To get value of group you want
*/
foreach (Match item in re.Matches("CP_01Ags_v5 CP_13Hgo_v5,"))
{
Console.WriteLine(" Match: " + item.ToString());
Console.WriteLine(" Your Target you want: " + item.Groups["YourTarget"]);
}