简体   繁体   中英

Regular expression for specific combination of alphabets and numbers

I am trying to create regular expression for following type of strings:

combination of the prefix (XI/ YV/ XD/ YQ/ XZ), numerical digits only, and either no 'Z' or a 'Z' suffix.

For example, XD35Z should pass but XD01HW should not pass.

So far I tried following:

  • @"XD\\d+Z?" - XD35Z passes but unfortunately it also works for XD01HW

  • @"XD\\d+$Z" - XD01HW fails which is what I want but XD35Z also fails

  • I have also tried @"XD\\d{1,}Z"? but it did not work

I need a single regex which will give me appropriate results for both types of strings.

Try this regex:

^(XI|YV|XD|YQ|XZ){1}\d+Z{0,1}$

I'm using quantifying braces to explicitly limit the allowed numbers of each character/group. And the ^ and $ anchors make sure that the regex matches only the whole line (string).

Broken into logical pieces this regex checks

  • ^(XI|YV|XD|YQ|XZ){1} Starts with exactly one of the allowed prefixes
  • \\d+ Is follow by one or more digits
  • Z{0,1}$ Ends with between 0 and 1 Z

You're misusing the $ which represents the end of the string in the Regex

It should be : @"^XD\\d+Z?$" (notice that it appears at the end of the Regex, after the Z? )

The regex following the behaviour you want is:

^(XI|YV|XD|YQ|XZ)\d+Z?$

Explanation:

combination of the prefix (XI/ YV/ XD/ YQ/ XZ)

^(XI|YV|XD|YQ|XZ)

numerical digits only

\d+

'Z' or a 'Z' suffix

Z?$

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