[英]c# Conditional Regular Expression String Match
I am trying to use c# Regular Expression to match a particular string of characters but I can not figure out how to do it. 我正在尝试使用c#正则表达式来匹配特定的字符串,但是我不知道该怎么做。 Any help is appreciated.
任何帮助表示赞赏。
The string that I am trying to match is as follows, where A is an uppercase alpha character, X is an upper case alpha-numeric character and # is 0, 1 or 2. 我要匹配的字符串如下,其中A是大写字母字符,X是大写字母数字字符,#是0、1或2。
AA-#-XX-X-XXX-XXXXXXX-XXXXXXXX
So any of the following would match the string above. 因此,以下任何内容都将与上面的字符串匹配。
XY-1
MM-0-AB
MM-0-AB-1-ABC-1234567
VV-2-XX-7-CCC-ABCDEFG-12345678
Any any of the following would NOT match. 以下任何一项都不匹配。
QQ-7-AA
(Only 0, 1, 2 are allowed at the second level.) QQ-7-AA
(第二级仅允许使用0、1、2。)
QQ-2-XX-7-CC
(Partial characters for that level.) QQ-2-XX-7-CC
(该级别的部分字符。)
QQ-2-XX-7-CCC-ABCDEFG-
(Can not end in a dash.) QQ-2-XX-7-CCC-ABCDEFG-
(不能以破折号结尾。)
QQ-2-XX-7-CCC-ABCDEFG-123456
(Partial characters for that level.) QQ-2-XX-7-CCC-ABCDEFG-123456
(该级别的部分字符。)
So far (not that far really) I have as the pattern to match @"^[AZ]{2}"
, but I am unsure how to match conditionally (I'm not even sure if conditionally is the proper term to use) the rest of the string, but only if it is there. 到目前为止(实际上不是那么远),我可以作为匹配
@"^[AZ]{2}"
,但是我不确定如何有条件地进行匹配(我不确定是否有条件地使用了正确的术语)字符串的其余部分,但前提是它在那里。 Do I need to write 7 different statements for this? 为此,我需要写7个不同的语句吗? Seems unreasonable, but I could be wrong.
似乎不合理,但我可能是错的。
Have a look at the Regular Expression Language . 看看正则表达式语言 。 You need the following elements:
您需要以下元素:
[AZ]
[AZ]
[A-Z0-9]
[A-Z0-9]
[0-2]
[0-2]
dash: -
破折号:
-
match x exactly n times: x{n}
精确匹配x次n次:
x{n}
x?
x?
(
... )
(
... )
Examples: 例子:
[AZ]{2}
[AZ]{2}
[AZ]{2}-
[AZ]{2}-
[AZ]{2}-[0-2]
[AZ]{2}-[0-2]
[AZ]{2}(-[0-2])?
Resulting expression: 结果表达式:
^[A-Z]{2}(-[0-2](-[A-Z0-9]{2}(-[A-Z0-9](-[A-Z0-9]{3}(-[A-Z0-9]{7}(-[A-Z0-9]{8})?)?)?)?)?)?$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.