Brett Allen
Brett Allen

Reputation: 5507

Grouping in Regex

I'm trying to do a match in regex.

It must match a string of characters of with the following 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.

Upvotes: 1

Views: 108

Answers (4)

nokturnal
nokturnal

Reputation: 2879

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.

Upvotes: 0

Oded
Oded

Reputation: 499362

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

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

Upvotes: 1

Jürgen Steinblock
Jürgen Steinblock

Reputation: 31743

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

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

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 839114

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.

Upvotes: 2

Related Questions