[英]C# Regular expression combination
I just wondered if I can combine these two expressions into one. 我只是想知道是否可以将这两个表达式合而为一。
Regex comb1 = new Regex("[A-Z0-9]{4,6}-[A-Z0-9]{4,6}-[A-Z0-9]{4,6}");
Regex comb2 = new Regex("[A-Z0-9]{4,6}-[A-Z0-9]{4,6}-[A-Z0-9]{4,6}-[A-Z0-9]{4,6}");
In general you would use alternations ( |
) to match one of a several patterns. 通常,您将使用交替( |
)来匹配多个模式之一。 For example: 例如:
aaa|bbb
Will first attempt to match the pattern aaa
and then attempt to pattern bbb
. 将首先尝试匹配模式aaa
,然后尝试模式bbb
。
However, because your patterns are so similar, you could just use something like this: 但是,由于您的模式是如此相似,因此您可以使用如下所示的内容:
[A-Z0-9]{4,6}(-[A-Z0-9]{4,6}){2,3}
This will match any sequence of four to six alphanumeric characters, followed by a hyphen and four to six alphanumeric characters, which must be repeated two or three times. 这将匹配四到六个字母数字字符的任何序列,后跟一个连字符和四到六个字母数字字符,必须重复两次或三遍。
If you have an optional part in a pattern, you can use (OptionalPattern)?
如果图案中有可选零件,可以使用(OptionalPattern)?
, so your code could become: ,因此您的代码可能变为:
[A-Z0-9]{4,6}-[A-Z0-9]{4,6}-[A-Z0-9]{4,6}(-[A-Z0-9]{4,6})?
But pswg's {2,3}
is a better choice here, since it also eliminates the unnecessary repetition in your pattern. 但是pswg的{2,3}
是一个更好的选择,因为它还消除了模式中不必要的重复。 I'm just mentioning since it can be useful in similar situations. 我只说这是因为它在类似情况下很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.