Home > database >  Matching repeating patterns in regex
Matching repeating patterns in regex

Time:06-06

I am trying to build a regular expression.

My input string is /KEYWORD/ANYTEXTHERE//ADDITIONALTEXT1//ADDITIONALTEXT2//ADDITIONALTEXT3//ADDITIONALTEXT4//ADDITIONALTEXT5//ADDITIONALTEXT6//ADDITIONALTEXT7

Key word and the text1 followed by / will always be present. For that I have tried

(\/KEYWORD\/(.*?)(\/\/|$))

The additional text followed by // can occur from 0 to 5 times in output. I am not sure of how this requirement can be satisfied using regex.

Forgive me this is my first question, I can explain better in comments.

CodePudding user response:

You can just use {6} next to the repeating syntax. So modifying your regex, it would look like this:

(\/KEYWORD\/((.*?)(\/\/|$)){6})

Which will capture up to the fifth ADDITIONAL TEXT

/KEYWORD/ANYTEXTHERE//ADDITIONALTEXT1//ADDITIONALTEXT2//ADDITIONALTEXT3//ADDITIONALTEXT4//ADDITIONALTEXT5//ADDITIONALTEXT6//ADDITIONALTEXT7

https://regex101.com/r/8VCzgv/1

Not sure if this fully answers your question, but if not, let me know.

  • Related