我有这个:
import java.util.regex.*;
String regex = "(?<m1>(hello|universe))|(?<m2>(hello world))";
String s = "hello world";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
while(matcher.find()) {
MatchResult matchResult = m.toMatchResult();
String substring = s.substring(matchResult.start(), matchResult.end());
System.out.println(substring);
}
Run Code Online (Sandbox Code Playgroud)
上面只打印,hello
而我想要打印hello world
.
解决这个问题的一种方法是重新排序组,String regex = "(?<m2>(hello world))|(?<m1>(hello|universe))"
但我无法控制我的情况下的正则表达式...
那么找到最长匹配的最佳方法是什么?一个显而易见的方法是检查s
这里提到的所有可能的子串(有效地找到正则表达式的所有重叠匹配)的长度并选择第一个但是就是这样O(n^2)
.我们可以做得更好吗?
$
只需在 Or 分隔符之前添加(End of string) 即可|
。
然后它检查字符串是否结束。如果结束,它将返回字符串。否则跳过正则表达式的该部分。
下面的代码给出了你想要的
import java.util.regex.*;
public class RegTest{
public static void main(String[] arg){
String regex = "(?<m1>(hello|universe))$|(?<m2>(hello world))";
String s = "hello world";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
while(matcher.find()) {
MatchResult matchResult = matcher.toMatchResult();
String substring = s.substring(matchResult.start(), matchResult.end());
System.out.println(substring);
}
}
}
Run Code Online (Sandbox Code Playgroud)
同样,下面的代码将跳过hello,hello world并匹配hello world there查看there
的用法$
import java.util.regex.*;
public class RegTest{
public static void main(String[] arg){
String regex = "(?<m1>(hello|universe))$|(?<m2>(hello world))$|(?<m3>(hello world there))";
String s = "hello world there";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
while(matcher.find()) {
MatchResult matchResult = matcher.toMatchResult();
String substring = s.substring(matchResult.start(), matchResult.end());
System.out.println(substring);
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3578 次 |
最近记录: |