Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit a regex capturing group?

I don't get how I can limit a capturing group.

If I have a regex like this:

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

I would think that this would capture any string with:

  • Exact two words,
  • With each word least 2 characters long,
  • And whole string no longer than 15 characters.

But the limiting of my capturing groups doesn't work. Can I limit capturing groups at all?

PS. I am using JavaScript to test the regexes in my examples.

like image 839
Nano Avatar asked Jun 13 '14 17:06

Nano


People also ask

How do I capture a group in regex?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".

How does group work in regex?

What is Group in Regex? A group is a part of a regex pattern enclosed in parentheses () metacharacter. We create a group by placing the regex pattern inside the set of parentheses ( and ) . For example, the regular expression (cat) creates a single group containing the letters 'c', 'a', and 't'.

What is Backreference in regular expression?

A backreference in a regular expression identifies a previously matched group and looks for exactly the same text again. A simple example of the use of backreferences is when you wish to look for adjacent, repeated words in some text. The first part of the match could use a pattern that extracts a single word.


1 Answers

This lookahead based regex should work for you:

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

Working Demo

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

like image 75
anubhava Avatar answered Sep 25 '22 23:09

anubhava