How to limit regex capture group?

I do not understand how to limit the capture group.

If I have a regex:

/^(\w{2,}\s\w{2,}){4,15}$/ 

I would think that this would capture any string with:

  • Exact two words,
  • For each word less than 2 characters long
  • And a whole line of no more than 15 characters.

But limiting my captured groups doesn't work. Can I limit capture groups at all?

PS. I use JavaScript to check for regular expressions in my examples.

+6
source share
1 answer

This view-based regular expression should work for you:

 /^(?=.{4,15}$)\w{2,}\s\w{2,}$/ 

Working demo

Your regular expression: ^(\w{2,}\s\w{2,}){4,15}$ basically means that there should be 4 to 15 instances of a string containing 2 words with at least two characters separated by space

+8
source

Source: https://habr.com/ru/post/970811/


All Articles