简体   繁体   中英

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 "-"

JZ 123456789 -301A
JZ 134255872 -22013

Between the string "JZ" and the last character

JZ 123456789 D

I have tried the following but it only works for the first example

(?<=JZ).*(?=-)

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

Try it out here

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM