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 match?
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.Matchreturns the first one, andRegex.Matchesboth 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:On the other hand, if you don’t want matching to be restricted to exactly 6 characters, change it to:
Or if you are looking to match 12 characters:
Of course, you might need a
^and$around the last 2 expressions too depending on your needs.