2

I've tried several patterns and fiddling with some pattern from Capture word between optional hyphens regex, Regular Expressions: How to find dashes between words, What's the difference between "(\w){3}" and "(\w{3})" in regex? and also read Reference - What does this regex mean?

My best attempt so far was: (\w{3}\-)

with test data:

THU-abs-sss-ddd

012-aa-aaa-aaa

which match:


Despite what I would like to achieve is an exact pattern validation against: XXX-XXX-XXX-XXX where XXX is 3 alphanumeric and dash repeated 3 times and closed with another XXX alphanumeric.

I've also tried using (\w{3}\-)(\w{3}) but then the result was:


What am I missing to complete the pattern?

Mukyuu
  • 4,695
  • 7
  • 32
  • 51
  • 1
    `^\w{3}(?:-\w{3}){3}$`. Quantify the group closer to the end of pattern, it is best practice. `^` matches the start of string and `$` matches the end of string, use these anchors if necessary. – Wiktor Stribiżew Nov 21 '19 at 08:40

1 Answers1

2

You need to repeat the \w{3}- group 3 times:

(?:\w{3}-){3}\w{3}

(note that - doesn't need to be escaped, and that you should use non-capturing groups unless you really need to capture)

CertainPerformance
  • 260,466
  • 31
  • 181
  • 209