简体   繁体   中英

Regex.Match() won't match a substring

This is something simple but I cannot figure this out. I want to find a substring with this regex. It will mach "M4N 3M5", but doesn't match the below :

const string text = "asdf M4N 3M5 adsf";
Regex regex = new Regex(@"^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$", RegexOptions.None);
Match match = regex.Match(text);
string value = match.Value; 

Try removing ^ and $:

Regex regex = new Regex(@"[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}", RegexOptions.None);
  • ^ : The match must start at the beginning of the string or line.
  • $ : The match must occur at the end of the string or before \\n at the end of the line or string.

If you want to match only in word boundaries you can use \\b as suggested by Mike Strobel:

    Regex regex = new Regex(@"\b[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}\b", RegexOptions.None);

I know this question has been answered but i have noticed two thing in your pattern which i want to highlight:

  1. No need to mention the single instance of any token.

    For example: (Notice the missing {1} )

    \\d{1} = \\d

    [AZ]{1} = [AZ]

  2. Also I won't recommend you to enter a <space> in your pattern use '\\s' instead because if mistakenly a backspace is pressed you might not be able to figure out the mistake and running code will stop working.

Personally, for this case i would recommend you to use \\b since it is best fit here.

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