Regex match checksum with or without dashes

Viewed 631

To match a dash-less checksum I can do something like:

\b[0-9a-z]{32}\b

However, I'm seeing some checksums that also have dashes, such as:

d3bd55bf-062f-473b-9417-935f62c4c98a

While this is probably a fixed size, 8, then 4, then 4, then 4, then 12, I was wondering if I could do a regex where the number of non-dash digits adds up to 32. I think the answer is no, but hopefully some regex wizard can come up with something.

Here is a starting point for some sample inputs: https://regex101.com/r/K0IMKe/1.

2 Answers

You can use

\b[0-9a-z](?:-?[0-9a-z]){31}\b

See the regex demo.

It matches

  • \b - a word boundary
  • [0-9a-z] - a digit or a lowercase ASCII letter
  • (?:-?[0-9a-z]){31} - thirty-one repetitions of an optional - followed with a single digit or a lowercase ASCII letter
  • \b - a word boundary.

If you do not mind having a trailing - if there is a word char after it, at the end of a match, you may also use

\b(?:[0-9a-z]-?){32}\b

See this regex demo. Here, (?:[0-9a-z]-?){32} will match thirty-two repetitions of a digit or lowercase ASCII letter followed with an optional hyphen.

If there can be multiple dashes, you can assert 32 to 36 chars using a positive lookahead.

^(?=[a-z0-9-]{32,36}$)[a-z0-9]+(?:-[a-z0-9]+)*$
  • ^ Start of string
  • (?=[a-z0-9-]{32,36}$) Positive lookahead, assert what is at the right is 32 - 36 repetitions of the listed characters
  • [a-z0-9]+ Match 1+ times any of the listed
  • (?: Non capture group
    • -[a-z0-9]+ Match a - followed by 1+ times any of the listed (the string can not end with a hyphen)
  • )* Close the group and match 0+ times to also match the string without dashes
  • $ End of string

Regex demo

If you want to limit the amount of dashes to 0 -4 times, you can change the quantifier * to {0,4}+

^(?=[a-z0-9-]{32,36}$)[a-z0-9]+(?:-[a-z0-9]+){0,4}+$

Regex demo

Related