如何限制正则表达式捕获组? [英] 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:
- 确切的两个字,
- 每个字长至少2个字符,
- 整个字符串不超过15个字符。
但限制我的捕获组不起作用。我可以限制捕获组吗?
But the limiting of my capturing groups doesn't work. Can I limit capturing groups at all?
PS。我正在使用JavaScript来测试我的示例中的正则表达式。
PS. I am using JavaScript to test the regexes in my examples.
推荐答案
这个基于前瞻性的正则表达式应该适合你:
This lookahead based regex should work for you:
/^(?=.{4,15}$)\w{2,}\s\w{2,}$/
工作演示
你的正则表达式: ^(\w {2,} \\\ {{2,}} { 4,15} $
基本上意味着应该有4到15个包含 2个单词的字符串实例,其中至少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
这篇关于如何限制正则表达式捕获组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!