Dejas
Dejas

Reputation: 3621

Not sure why I can't match this regex in C#

I'm trying to match the string "September 12" with the following C# code. But it won't match and I'm not sure why. What am I doing wrong? It appears to work on regexpal.com

public static void Scan(String str)
    {
        String digits = "(0|1|2|3|4|5|6|7|8|9)";

        String r1 = "September " + digits + "+";

        foreach (Match match in Regex.Matches(str, r1, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace))
        {
            String value = match.Value;
        }


    }

Upvotes: 2

Views: 221

Answers (4)

Frank Hale
Frank Hale

Reputation: 1896

You could try it this way.

public static void Scan(String str)
{
  // This regex is pretty nasty, I would probably take more time to refine it.
  String patt = @"^([A-Za-z]+)(\s)(\d+)$";

  foreach (Match match in Regex.Matches(str, patt, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace))
  {
    String value = match.Value;

    Console.WriteLine(value);
  }
}

...

Then call it like:

Scan("September 2011");

Upvotes: 0

Abe Miessler
Abe Miessler

Reputation: 85046

As @Moritz pointed out your are not matching because you are Ignoring Whitespace. You should also note that your current method will match a wide range of "dates" that are invalid. September 67 for instance.

I would recommend using a slightly more complex pattern for matching the number pattern:

September ([1-9]|[12][0-9]|3[01])

This will limit the numbers to between 1 and 31. While this will still allow some invalid dates (September 31 for instance) it will greatly limit the number of invalid dates matched.

Upvotes: 2

Moritz Both
Moritz Both

Reputation: 1628

The problem is the flag RegexOptions.IgnorePatternWhitespace. Remove it since you don't want to ignore whitespace in the regular expression - you need it to match the whitespace between "September" and "19".

Hint: digits can be written more easy as [0-9]. A better regular expression would be

September [0-9]+

Upvotes: 7

Kevin Kalitowski
Kevin Kalitowski

Reputation: 6989

@"September\s\d+" should do it

The \s matches a space, the \d matches any digit, and the + is 1 or more of the preceding.

Upvotes: 0

Related Questions