Home > Blockchain >  Repeting pattern in Regex - Javascript
Repeting pattern in Regex - Javascript

Time:10-19

I'm struggling to match a pattern in regex that simulate a nested tree with words separated by dots, and leaf node separated by "->" or not.

It should start with "$".

words should be formed by \w{1,32} only

I'm using javascript

ex:

$any.number.of.words.followed.by.dot.and.final.word.followed.by.arrow.or->not

$root.f1.f2->col4 -OK (complete)

$f4.folder7 -OK (do not have the leaf node)

$f1->col7 -OK (just root and leaf node)

$root.g5.tt.dd...bbh.hht.sdwswsw->col7 -NOK ("..." is wrong)

$.ferf->45 -NOK (words should have at least one \w)

$$e.fe.45 - NOK (starts with $$)

$feefefefefefefefe -NOK (should have at least one "." or "->"

My goal is to have 2 patterns, one that includes leaf node (->), and one without it

without leaf node: /\$[\w \.] /

with leaf node: /\$[\w \.] ->\w /

It works for the most of the cases, but it fails to identify NOK examples above.

My real question is how I define a short pattern to repeat using quantifiers ? when I use quantifiers, it always consider repetition of the last symbol How to find repetition for the following pattern ? \w{1,32}.\{1}

CodePudding user response:

For a single pattern for both variations, you can optionally repeat the dots and the word chars, and optionally match the -> and word chars, or match only the -> part

^\$\w{1,32}(?:(?:\.\w{1,32}) (?:->\w{1,32})?|->\w{1,32})$
  • ^ Start of string
  • \$\w{1,32} Match $ and 1-32 word chars
  • (?: Non capture group
    • (?:\.\w{1,32}) Match 1 repetitions of . and 1 - 32 word chars
    • (?:->\w{1,32})? Optionally match -> and word chars
    • | Or
    • ->\w{1,32} Match -> and word chars
  • ) Close non capture group
  • $ End of string

Regex demo

A separate pattern without a leaf node, where there are 1 repetitions of a dot and word characters till the end of string

^\$\w{1,32}(?:\.\w{1,32}) $

Regex demo

A separate pattern with a leaf node, where there are optional repetitions of a dot and word characters and a mandatory -> part:

^\$\w{1,32}(?:\.\w{1,32})*->\w{1,32}$

Regex demo

  • Related