Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe separated values in groups of 3 regex

Tags:

regex

I have the following string

abc|ghy|33d

The regex below matches it fine

^([\d\w]{3}[|]{1})+[\d\w]{3}$

The string changes but the characters separated by the pipe are always in 3's ... so we can have

krr|455

we can also have

ddc

Here's where the problem happens: The regex explained above doesn't match the string if there is only one set of letters ... i.e. "dcc"

like image 688
Drmjo Avatar asked Dec 14 '25 12:12

Drmjo


1 Answers

Let's do this step by step.

Your regex :

^([\d\w]{3}[|]{1})+[\d\w]{3}$

We can already see some changes. [|]{1} is equivalent to \|.
Then, we see that you match the first part (aaa|) at least once (the + operator matches once at least). Also, \w matches numbers.
The * operator matches 0 or more. So :

^(?:\w{3}\|)*\w{3}$

works.

See here.

Explanation

^ Matches beggining of string
(?:something)* matches something zero time or more. the group is non-capturing as you won't need to
\w{3} matches 3 alphanumeric characters
\| matches |
$ matches end of string.

like image 161
Docteur Avatar answered Dec 19 '25 07:12

Docteur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!