限制捕获组字符数 [英] Limit number of character of capturing group
问题描述
假设我有这样的文字:"AAAA1 AAA11 AA111AA A1111 AAAAA AAAA1111"
.
Let's say i have this text : "AAAA1 AAA11 AA111AA A1111 AAAAA AAAA1111"
.
我想找到符合这 3 个条件的所有事件:
-大写字母 1 到 4 次
-数字1到4次
-最大字符数为 5
I want to find all occurrences matching these 3 criteria :
-Capital letter 1 to 4 times
-Digit 1 to 4 times
-Max number of characters to be 5
所以匹配将是:{"AAAA1", "AAA11", "AA111", "A1111", "AAAA1"}
我试过了
([A-Z]{1,4}[0-9]{1,4}){5}
但我知道它会失败,因为它正在寻找我的团队五次.
but i knew it would fail, since it's looking for five time my group.
有没有办法将组的结果限制为 5 个字符?
Is there a way to limit result of the groups to 5 characters?
谢谢
推荐答案
您可以在检查匹配部分的模式时提前限制字符数.
You can limit the character count with a look ahead while checking the pattern with you matching part.
如果你可以用空格分割输入,你可以使用:
If you can split the input by whitespace you can use:
^(?=.{2,5}$)[A-Z]{1,4}[0-9]{1,4}$
请参阅此处的演示.
如果你不能用空格分割你可以用 (?:^| )(?=.{2,5}(?=$| ))([AZ]{1,4}[0-9]{1,4})(?=$| )
例如,或lookbehind 或 \K
根据您的正则表达式风格进行拆分(请参阅 演示).
If you cannot split by whitespace you can use capturing group with (?:^| )(?=.{2,5}(?=$| ))([A-Z]{1,4}[0-9]{1,4})(?=$| )
for example, or lookbehind or \K
to do the split depending on your regex flavor (see demo).
PREVIOUS ANSWER,错误匹配A1A1A
,在@a_guest 评论后更新.
PREVIOUS ANSWER, wrongly matches A1A1A
, updated after @a_guest remark.
您可以使用前瞻来检查您的模式,同时使用正则表达式的匹配部分限制字符数:
You can use a lookahead to check for your pattern, while limiting the character count with the matching part of the regex:
(?=[A-Z]{1,4}[0-9]{1,4}).{2,5}
请参阅此处的演示.
这篇关于限制捕获组字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!