简体   繁体   中英

Regex Match .Net

Im Using this Code with to Match

 var regex = new Regex(@"\[0-9]{3,4}/?\s?\\?\-?_?[A-Z]{2,2}-?\s?/?_?\\?[A-Z]{2,2}");

var match = regex.Match(str);
if (match.Success)
{
   Console.WriteLine(match.Value);
   Console.ReadLine();
}

this string : 1111 CD XZ and Also this one 1111/AB-XZ But is not working , im on my Intial steps on programming I just yesterday I started to use Regex. Im doing some wrong ?

My Goal Is to Match The yellow mark on this Image

Your regex is corrupt since the \\ before [ makes the regex engine match a literal [ symbol while you wanted to create a character class. Besides, rather than define a sequence of optional chars, you may just define a non-word optional pattern for the separators in your string.

You may use

@"\b[0-9]{3,4}(?:\W?[A-Z]{2}){2}\b"

See the regex demo

Details

  • \\b - a word boundary (to make sure you really match a 3 to 4 digit sequence later)
  • [0-9]{3,4} - 3 to 4 digits
  • (?:\\W?[AZ]{2}){2} - 2 sequences of
    • \\W? - an optional non-word char (whitespace, punctuation or symbol)
    • [AZ]{2} - 2 uppercase ASCII letters
  • \\b - a trailing word boundary.

使用这个正则表达式(?i)\\d{3,4}[\\s\\/]\\/?[az]{2}[-\\s][az]{2}

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