Reputation: 607
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}");
Upvotes: 0
Views: 170
Reputation: 421
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.
Upvotes: 1
Reputation: 149020
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.
Upvotes: 4