Reputation: 6226
I'm trying to come up with a regular expression matches the text in bold in all the examples.
Between the string "JZ" and any character before "-"
JZ123456789-301A
JZ134255872-22013
Between the string "JZ" and the last character
JZ123456789D
I have tried the following but it only works for the first example
(?<=JZ).*(?=-)
Upvotes: 2
Views: 175
Reputation: 23521
A one-line answer without regex:
string s,r;
// if your string always starts with JZ
s = "JZ123456789-301A";
r = string.Concat(s.Substring(2).TakeWhile(char.IsDigit));
Console.WriteLine(r); // output : 123456789
// if your string starts with anything
s = "A12JZ123456789-301A";
r = string.Concat(s.Substring(s.IndexOf("JZ")).TakeWhile(char.IsDigit));
Console.WriteLine(r); // output : 123456789
Basically, we remove everything before and including the delimiter "JZ", then we take each char while they are digit. The Concat
is use to transform the IEnumerable<char>
to a string. I think it is easier to read.
Upvotes: 0
Reputation: 626699
You may use
JZ([^-]*)(?:-|.$)
and grab Group 1 value. See the regex demo.
Details
JZ
- a literal substring([^-]*)
- Capturing group 1: zero or more chars other than -
(?:-|.$)
- a non-capturing group matching either -
or any char at the end of the stringC# code:
var m = Regex.Match(s, @"JZ([^-]*)(?:-|.$)");
if (m.Success)
{
Console.WriteLine(m.Groups[1].Value);
}
If, for some reason, you need to obtain the required value as a whole match, use lookarounds:
(?<=JZ)[^-]*(?=-|.$)
See this regex variation demo. Use m.Value
in the code above to grab the value.
Upvotes: 1
Reputation: 2991
You can use (?<=JZ)[0-9]+
, presuming the desired text will always be numeric.
Upvotes: 3