Pipe split values ​​in groups of 3 regexp

I have the following line

abc|ghy|33d

      

Following is the regex

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

      

The string changes, but the pipe-separated characters are always in 3 ... so we can have

krr|455

      

we can also have

ddc

      

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

+3


source to share


4 answers


Take it step by step.

Your regex:

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

      

We are already seeing some changes. [|]{1}

is equivalent \|

.
We then see that you agree to the first part (aaa |) at least once (the + operator matches at least once). It also \w

matches the numbers.
The * operator matches 0 or more. So:

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

      



work.

See here .

Description

^

A
(?:something)*

match at the beginning of a line corresponds to zero or more times. group does not capture because you do not need to \w{3}

match 3 alphanumeric characters
\|

matches |
$

matches the end of the line.

+1


source


^[\d\w]{3}(?:[|][\d\w]{3}){0,2}$

      

You are simply quantifying the variable part.See demo.



https://regex101.com/r/tS1hW2/18

0


source


You can change your regex like below:

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

      

here the first match is 3 alphaNumeric

and thenalphaNum with | as prefix.

Demo

0


source


Your description is a bit awkward, but I assume you want to be able to match

abc
abc|def
abc|def|ghi

      

You can do it with

/^\w{3}(?:\|\w{3}){0,2}$/

      

Visualization

/ ^ \ w {3} (?: \ | \ w {3}) {0,2} $ /

Explanation

  • ^

    - the beginning of the beginning of the line
  • \w{3}

    - match any 3 of [A-Za-z0-9_]

  • (? ... )?

    - non-capturing group, 0 or 1 matches
  • \|

    - literal |

    symbol
  • $

    - end of line

If the goal is to match any number of 3-letter segments, you can use

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

      

0


source







All Articles