2

I have String that can be for example 3D-F2-C9-A6-B3

This is my regex and I've validated it by an online regex tester:

^([0-9A-Fa-f]{2}[-]){0,}$

The problem is, that the example string 3D-F2-C9-A6-B3-4F is not valid. I have to add a minus at the end like 3D-F2-C9-A6-B3-4F-

How can I change the regex that the separators in the middle have to be set but no one at the end?

1 Answer 1

2

The best way is to unroll it a bit:

^[0-9A-Fa-f]{2}(?:-[0-9A-Fa-f]{2})*$

See the regex demo

Details:

  • ^ - start of string
  • [0-9A-Fa-f]{2} - 2 chars from the defined set
  • (?:-[0-9A-Fa-f]{2})* - zero or more sequences of
    • - - a literal hyphen
    • [0-9A-Fa-f]{2} - 2 chars from the defined set
  • $ - end of string (better option is \z to match the very end of the string)

C# demo:

var pattern = @"^[0-9A-Fa-f]{2}(?:-[0-9A-Fa-f]{2})*\z";
var input = "3D-F2-C9-A6-B3";
var matched = Regex.IsMatch(input, pattern); // = > True
Sign up to request clarification or add additional context in comments.

1 Comment

Often, people post a solution like ^([0-9A-Fa-f]{2}[-]?){0,}$ (note a ? in [-]?). This way, matching is becoming non-linear, it also allows - to appear at the end of the string, and in some cases leads to poorer performance with very long strings. Repeating the pattern like yours ([0-9A-Fa-f]) is not a big problem here (you can even shorten it using RegexOptions.IgnoreCase and removing A-Z), else just build the pattern dynamically by defining a variable with the repeated block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.