Java 中的正则表达式在替代匹配中使用相同的组
Regex in Java use same group in alternative matches
我有一个匹配不同表达式的正则表达式模式,但我希望两个匹配项都在同一个捕获组中。
目前我得到以下正则表达式:
-([^\s"]+)|-"(.+?)"
这实际上匹配两个 (-hello -"Hello World"),但在不同的组中(-hello = group1 和“Hello World”= group2)。
事实上我得到了一个工作示例,不幸的是在 Java 正则表达式中是不可能的:
(?|-([^\s"]+)|-"(.+?)")
只需使用正则表达式模式匹配器并检查两个捕获组,使用不为空的一个:
String input = "-hello -\"Hello World\"";
String pattern = "-([^\s\"]+)|-\"(.+?)\"";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
while (m.find()) {
String match = !Objects.isNull(m.group(1)) ? m.group(1) : m.group(2);
System.out.println("Found a match: " + match);
}
这会打印:
Found a match: hello
Found a match: Hello World
一种选择是使用环视断言,这样您就可以摆脱所有捕获组并在结果中获得完全匹配:
(?<=-)[^\s"]+|(?<=-")[^"]*(?=")
Pattern p = Pattern.compile("(?<=-)[^\s\"]+|(?<=-\")[^\"]*(?=\")");
List<String> res = p.matcher("(-hello -\"Hello World\")")
.results()
.map(MatchResult::group)
.collect(Collectors.toList());
//=> [hello, Hello World]
我有一个匹配不同表达式的正则表达式模式,但我希望两个匹配项都在同一个捕获组中。 目前我得到以下正则表达式:
-([^\s"]+)|-"(.+?)"
这实际上匹配两个 (-hello -"Hello World"),但在不同的组中(-hello = group1 和“Hello World”= group2)。
事实上我得到了一个工作示例,不幸的是在 Java 正则表达式中是不可能的:
(?|-([^\s"]+)|-"(.+?)")
只需使用正则表达式模式匹配器并检查两个捕获组,使用不为空的一个:
String input = "-hello -\"Hello World\"";
String pattern = "-([^\s\"]+)|-\"(.+?)\"";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
while (m.find()) {
String match = !Objects.isNull(m.group(1)) ? m.group(1) : m.group(2);
System.out.println("Found a match: " + match);
}
这会打印:
Found a match: hello
Found a match: Hello World
一种选择是使用环视断言,这样您就可以摆脱所有捕获组并在结果中获得完全匹配:
(?<=-)[^\s"]+|(?<=-")[^"]*(?=")
Pattern p = Pattern.compile("(?<=-)[^\s\"]+|(?<=-\")[^\"]*(?=\")");
List<String> res = p.matcher("(-hello -\"Hello World\")")
.results()
.map(MatchResult::group)
.collect(Collectors.toList());
//=> [hello, Hello World]