Home > Software engineering >  Regex- Whitespace is not working to get an integer value
Regex- Whitespace is not working to get an integer value

Time:10-30

I am trying to get a pattern match using Regex. If the message has space after the pattern string, its getting a empty string.

string str = "studentId: 1234, Name: Hello";
Regex reg = new Regex(@"studentId:(\d*)", RegexOptions.IgnoreCase);

Match m = reg.Match(str);
Group g = m.Groups[1];
int Id = int.Parse(g.ToString());

studentId:1234 (Working) studentId: 1234 (Not Working) studentId: 1234 (Not Working)

I need to get the value 1234 irrespective of spaces.

CodePudding user response:

Yes, you need to match it

Regex reg = new Regex(@"studentId:\s*(\d )", RegexOptions.IgnoreCase);

Details:

  • studentId: - a fixed string
  • \s* - zero or more whitespaces
  • (\d ) - one or more digits (Group 1).
  • Related