简体   繁体   中英

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;
        }


    }

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]+

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.

@"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.

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");

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