开发者

C# Regex matches aabbccddeeff as two aabbcc and ddeeff sets

开发者 https://www.devze.com 2023-01-19 02:59 出处:网络
When I do this: var m = Regex.Match(\"aabbccddeeff\", \"[0-9a-fA-F]{6}\"); I get only aabbcc as result. Actually (using .Matches) there\'re two matches: aabbcc and ddeeff.

When I do this:

var m = Regex.Match("aabbccddeeff", "[0-9a-fA-F]{6}");

I get only aabbcc as result. Actually (using .Matches) there're two matches: aabbcc and ddeeff.

Why? This causes issues with DataAnnotations.RegularExpressionAttribute because it expects single match that covers whole input value.

How do I write this properly to get a single matc开发者_JAVA百科h?


What is it that you are trying to achieve here?

The regular expression provided will try to match a sequence of exactly 6 letters / digits. Since there are 12 consecutive alphanumeric characters in the input, there are 2 consecutive matches. Regex.Match returns the first one, and Regex.Matches both of them, exactly as they should.

If you want to assert that the entire text will precisely match the regex (since you are using it for input validation, I assume this is the case), so that the entire input string should satisfy Regex.IsMatch, change the expression to:

^[0-9a-fA-F]{6}$

On the other hand, if you don't want matching to be restricted to exactly 6 characters, change it to:

[0-9a-fA-F]+ 

Or if you are looking to match 12 characters:

[0-9a-fA-F]{12}

Of course, you might need a ^ and $ around the last 2 expressions too depending on your needs.


From the documentation for Match: "This method returns the first substring in input that matches the regular expression pattern. You can retrieve subsequent matches by repeatedly calling the returned Match object's Match.NextMatch method. You can also retrieve all matches in a single method call by calling the Regex.Matches(String) method."

If you only want the first match then you need to modify your regular expression. Try "^[0-9a-fA-F]{6}"


Well. You are matching the character set 0-9, a-f, A-F 6 times.

If you want to match the entire string, group the expression. ([0-9a-fA-F])*. If you want at least once result, replace * with a +.

0

精彩评论

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