-1

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!

3
  • possible duplicate of How to extract a substring from a .NET RegEx? Commented Jan 9, 2014 at 18:57
  • This would be quite simple to find out yourself... Commented Jan 9, 2014 at 18:58
  • I looked through tutorials, and was having a hard time understanding the various explanations. I understand that it is simple, I just wanted to see how others might explain it. I appreciate your insight though! Commented Jan 9, 2014 at 19:09

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Ah was just about to hit submit to send this in!
So \d results in an Unrecognized escape sequence, any thoughts?
in C# you'll have to escape the `, so use \\d`.
2

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.

3 Comments

This wouldn't catch 'Working on log #34'.
@MadSkunk that was true before I finished my edit :)
Indeed, consider my comment no longer valid :)
1

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

Comments

0

A capturing group is the solution:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.