我有模式“abc|de.|ghi”和“def”的输入。如何找到匹配“def”的模式部分?所以,在这个例子中,我想要的结果是“de.”。不是“def”,这是我使用组和开始/结束方法所能获得的全部。
在代码中:
Pattern p = Pattern.compile("abc|de.|ghi");
Matcher m = p.matcher("def");
if(matcher.find()) {
// Here I want to get the String "de." somehow
}
最佳答案
有点绕,但是你可以用捕获组做你想做的事:
Pattern p = Pattern.compile("(abc)|(de.)|(ghi)");
Matcher m = p.matcher("def");
if(m.find()) {
if (m.group(1) != null)
System.out.println("Matched \"abc\"");
if (m.group(2) != null)
System.out.println("Matched \"de.\"");
if (m.group(3) != null)
System.out.println("Matched \"ghi\"");
}
关于java - 如何找到与 java 中的输入匹配的正则表达式模式部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17480546/