-2

I have a string and I want to capture the number inside it and then add one to it!.

For example I have an email subject header saying "Re: Hello (1)"

I want to capture that 1 and then raise it by 2, then 3,then 4,etc. The difficulty I am having is taking into consideration the growing numbers, once it becomes say 10 or 100, that extra digit kills my current Regex expression.

      int replyno = int.Parse(Regex.Match(Subject, @"\([0-9]+\)").Value);
      replyno++;
      string Subject = Subject.Remove(Subject.Length - 3);
      TextBoxSubject.Text = Subject + "("+replyno+")";
AnonJr
  • 2,759
  • 1
  • 26
  • 39
Pearce
  • 320
  • 4
  • 10

3 Answers3

2

Re: Hello \([0-9]+\)

This matches the string "Re: Hello (1)" with any number of digits as the number, so it also matches "Re: Hello (100)".

Note that I have specifically used [0-9] and not \d to match a digit, because they are different. \d will match numeric characters in other languages, too. See this question and answer for more info: https://stackoverflow.com/a/6479605/1801

If you need to match other numeric characters, you can replace [0-9] with \d

Community
  • 1
  • 1
Slavo
  • 15,255
  • 11
  • 47
  • 60
1

You may use

\((\d+)\)

as a regular expression. This captures a number inside (), regardless of the numbers size thanks to +.

KeyNone
  • 8,745
  • 4
  • 34
  • 51
0

Change your regex expression to \d+. That'll help you support multi-digit numbers.

David Arno
  • 42,717
  • 16
  • 86
  • 131