Daniel
Daniel

Reputation: 4342

capturing a repeating pattern with regex

I'm trying to match a pattern like this CODE-UH87H-98HSH-HB383-JWWB2U and I have the following regex pattern CODE\-[A-Z0-9]+\-[A-Z0-9]+\-[A-Z0-9]+\-[A-Z0-9]+ but is there a better way of doing this? I tried CODE(\-[A-Z0-9]+\-){4} and it didn't work

Upvotes: 0

Views: 96

Answers (3)

Marcus Gründler
Marcus Gründler

Reputation: 975

When the pattern between the dashes may contain any character, the following regex is even shorter:

CODE(-[^-]+){4}

Of course you may have to add \ for escaping before the dash depending on what regex engine you will use.

Upvotes: 0

Mattias Farnemyhr
Mattias Farnemyhr

Reputation: 4238

You were almost there. CODE(\-[A-Z0-9]+){4} should work!

Upvotes: 0

Bergi
Bergi

Reputation: 664484

I tried CODE(\-[A-Z0-9]+\-){4} and it didn't work

That does require two dashes in succession. In full, it would be CODE\-[A-Z0-9]+\-\-[A-Z0-9]+\-\-[A-Z0-9]+\-\-[A-Z0-9]+\-. What you want is

CODE(\-[A-Z0-9]+){4}

Upvotes: 1

Related Questions