简体   繁体   中英

get number from a string after trimming 0 using Regex c#

I have a namestring like ( This is a file name stored in server)

Offer_2018-06-05_PROSP000033998_20180413165327.02155000.NML.050618.1040.67648.0

The file name format is given above. I need to get the number out of

PROSP000033998

and remove the leading zeros ( 33998) using Regex in C# . there are different values that will come instead of PROSP. So i want to use a regex to get the number instead of string split. Tried using (0|[1-9]\\d*) , but not sure whether this is correct as i got 2018 as the output

  Regex regexLetterOfOffer = new Regex (@"0|[1-9]\d*");
                            Match match = regexLetterOfOffer.Match (fileInfo.Name);
                            if (match.Success)
                            {
                                Console.WriteLine (match.Value);
                            }

Putting (0|[1-9]\\d*) into https://java-regex-tester.appspot.com/ shows that it is actually matching the number you want, it's just also matching all the other numbers in the string. The Match method only returns the first one, 2018 in this case. To only match the part you're after, you could use PROSP0*([1-9]\\d*) as the regex. The brackets () around the last part make it a capturing group , which you can retrieve using the Groups property of the Match object:

Console.WriteLine(match.Groups[1].Value)

(Group 0 is the whole match, hence we want group 1.)

A generalized regular expression for alphabetical characters, possibly followed by zeros, then capturing digits with an underscore afterwards could be

[A-Z]0*([1-9]\d*)(?=_)

That is:

Regex regexLetterOfOffer = new Regex (@"[A-Z]0*([1-9]\d*)(?=_)");
Match match = regexLetterOfOffer.Match("Offer_2018-06-05_PROSP000033998_20180413165327.02155000.NML.050618.1040.67648.0");
if (match.Success)
{
  Console.WriteLine (match.Groups[1].Value);
}

This will match similar strings whose digit sequences start with something other than PROSP .

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