Java模式匹配器组定义
我有一个简单的正则表达式,看起来像
([az]*)( +[az]="[0-9]")*
它适用于匹配模式
test a="1" b="2" c="3"...
有没有办法在单独的匹配器组中捕获每个名称 – 值对(例如,a =“1”)?
正如在上面的例子中,我获得了(测试)的匹配器组,并且只有一个匹配器组用于3个名称 – 值对(即,最后一个,c =“3”)。 我预计会有3个匹配组,每对组合1个。
我预计会有3个匹配组,每对组合1个。
不,总共有两组。 获得三组键值对的唯一方法是:
([az]*)( +[az]="[0-9]")( +[az]="[0-9]")( +[az]="[0-9]")
您可以匹配单个组中的所有键值对,然后在其上使用单独的Pattern&Matcher:
import java.util.regex.*; public class Main { public static void main(String[] args) throws Exception { String text = "test a=\"1\" b=\"2\" c=\"3\" bar d=\"4\" e=\"5\""; System.out.println(text + "\n"); Matcher m1 = Pattern.compile("([az]*)((?:[ \t]+[az]=\"[0-9]\")*)").matcher(text); while(m1.find()) { System.out.println(m1.group(1)); Matcher m2 = Pattern.compile("([az])=\"([0-9])\"").matcher(m1.group(2)); while (m2.find()) { System.out.println(" " + m2.group(1) + " -> " + m2.group(2)); } } } }
产生:
test a="1" b="2" c="3" bar d="4" e="5" test a -> 1 b -> 2 c -> 3 bar d -> 4 e -> 5
使用Matcher#find()
方法切换到下一组。
在循环中执行,例如:
Matcher matcher = pattern.matcher(test); while (matcher.find()) { //extract groups here }
从来没听说过。 但是如果你匹配\s+\w="\d"
,那么你可以多次调用find
并自己处理每个匹配。