Robert
Robert

Reputation: 6226

Regular expression match between string and last digit

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

Answers (3)

aloisdg
aloisdg

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.

Try it online

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

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 string

C# 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

Callum Watkins
Callum Watkins

Reputation: 2991

You can use (?<=JZ)[0-9]+, presuming the desired text will always be numeric.

Try it out here

Upvotes: 3

Related Questions