长度前为(length)%代码的模式匹配



我有一个类似x%c的模式,其中x是一个个个位数的整数,c是长度为x的字母数字代码。%只是长度和代码的标记分隔符

例如,2%74是有效的,因为74是2位数字。同样,1%8和4%3232也是有效的。

我已经尝试了形式为^([0-9]((%(([A-GZ0-9]({\1}的正则表达式,其中我试图通过组1的值来限制长度。它显然不起作用,因为组被视为字符串,而不是数字。

如果我将上面的正则表达式更改为^([0-9]((%(([A-GZ0-9]({2},它将适用于2%74,这是没有用的,因为我的长度将由第一组而不是固定数字控制。

我不可能用正则表达式,在java中有更好的方法吗?

一种方法可以使用两个捕获组,将第一个组转换为int,并计算第二个组的字符数。

b(d+)%(d+)b
  • b字边界
  • (d+)捕获组1,匹配1+个数字
  • %按字面匹配
  • (d+)捕获组2,匹配1+个数字
  • b字边界

Regex演示| Java演示

例如

String regex = "\b(\d+)%(\d+)\b";
String string = "2%74";
Pattern pattern = Pattern.compile(regex);
String strings[] = { "2%74", "1%8", "4%3232", "5%123456", "6%0" };
for (String s : strings) {
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
if (Integer.parseInt(matcher.group(1)) == matcher.group(2).length()) {
System.out.println("Match for " + s);
} else {
System.out.println("No match for " + s);
}
} 
}

输出

Match for 2%74
Match for 1%8
Match for 4%3232
No match for 5%123456
No match for 6%0

最新更新