admin管理员组

文章数量:1336434

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.

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.

Share Improve this question edited Jun 16, 2014 at 19:32 Amal 76.7k18 gold badges132 silver badges153 bronze badges asked Jun 13, 2014 at 17:31 NanoNano 1,3986 gold badges20 silver badges33 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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

本文标签: javascriptHow to limit a regex capturing groupStack Overflow