简体   繁体   中英

.NET Regex - Specific String containing a changing number

I am new to working with Regexs in C# .NET. Say I have a string as follows...

"Working on log #4"

And within this string we can expect to see the number (4) vary. How can I use a Regex to extract only that number from the string.

I want to make sure that the string matches the first part:

"Working on log #"

And then exctract the integer from it.

Also - I know that I could do this using string.Split(), or .Substring, etc. I just wanted to know how I might use regex's to do this.

Thanks!

"Working on log #(\d+)"

The () create a match group, so you will be able to extract that section.
The \\d matches any digit.
The + says "look at the previous token, match it one or more times" so it will make it match one or more digits.

So overall you're capturing a group containing one or more digits, where that group comes after "Working on log #"

RegEx rgx = new RegEx("Working on log #[0-9]"); is the pattern you want to use. The first part is a string literal, [0-9] says that character can be any value 0 through 9. If you allow multiple digits then change it to [0-9]{x} where x is the number of repetitions or [0-9]+ as a + after any character means 1 or more of that character is allowed.

You could also just do string.StartsWith("Working on log #") then split on # and use int.TryParse() with the second value to confirm it is in fact a valid integer.

Try this: ^(?<=Working on log #)\\d+$ . This only captures the number. No need for a capture group. Remove ^ and $ if this is within a larger string.

  • ^ - start of string
  • (?<=) - positive lookbehind - ensures what is between = and ) is found before
  • \\d+ - at least one digit
  • $ - end of string

A capturing group is the solution:

"Working on log #(?<Number>[0-9]+)"

Then you can access the matched groups using the Match.Groups property.

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