简体   繁体   English

用于字母和数字的特定组合的正则表达式

[英]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. 前缀(XI / YV / XD / YQ / XZ)的组合,仅数字,无“ Z”或“ Z”后缀。

For example, XD35Z should pass but XD01HW should not pass. 例如, XD35Z应该通过但XD01HW不应该通过。

So far I tried following: 到目前为止,我尝试了以下操作:

  • @"XD\\d+Z?" - XD35Z passes but unfortunately it also works for XD01HW XD35Z通过,但不幸的是,它也适用于XD01HW

  • @"XD\\d+$Z" - XD01HW fails which is what I want but XD35Z also fails @"XD\\d+$Z" XD01HW失败,这是我想要的,但XD35Z也失败

  • I have also tried @"XD\\d{1,}Z"? 我也尝试过@"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 ^(XI|YV|XD|YQ|XZ){1}以正好允许的前缀之一开头
  • \\d+ Is follow by one or more digits \\d+后跟一位或多位数字
  • Z{0,1}$ Ends with between 0 and 1 Z Z{0,1}$以0至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? ) 它应该是: @"^XD\\d+Z?$" (注意,它出现在Regex的末尾,在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)

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

numerical digits only 仅数字

\d+

'Z' or a 'Z' suffix “ Z”或“ Z”后缀

Z?$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM