简体   繁体   中英

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 .

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)? , 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. I'm just mentioning since it can be useful in similar situations.

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