开发者

Grouping in Regex

I'm trying to do a match in regex.

It must match a string of characters of with the follow开发者_C百科ing formats:

Start with a C or H, w/ 6 characters following. (Total 7 characters long) Start with KK and with 8 characters following. (Total 10 characters long)

The field is limited to 10 typed characters. I have the following:

(((C|H).{6})|(KK.{8}))

It matches KK+8 just fine. It fails on C+5 just fine. It succeeds on C+6 just fine. However it succeeds on C+7,C+8 and C+9.

I'm assuming my grouping is wrong, can anyone point out my error?

This is .NET flavored Regex and I'm using Regex.IsMatch to determine if the field exactly matches my regex.


You need to anchor the start (^) and end ($) of the string:

^([CH].{6}|KK.{8})$

I've also trimmed out the unnecessary parentheses and changed (C|H) to a character class to improve readability.


You you want to capture anything from the pattern? If not, I would try this one:

^(KK..|C|H).{6}$


You need to add the start and end of line anchors:

^(((C|H).{6})|(KK.{8}))$


I like Mark Byers answer best, with this modification (tested for .NET):

^[CH].{6}$|^KK.{8}$

The original will give a false match for values with more than 6 characters after a C or H.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜