我试图找到所有出现的“.-”。在此字符串“-.-.-.-”中,所以我期望输出为 2,但我只得到 1。
如果我搜索这个字符串“-.-.--.--.-.--”,我期望 2,并且确实得到 2。所以在我看来,搜索无法识别单个“。 -”当他们彼此相邻分组时。我该如何解决这个问题?
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test {
public static void find() {
int count = 0;
Pattern p = Pattern.compile("\\.-\\.");
Matcher m = p.matcher("-.-.-.-");
while (m.find()) {
count++;
}
System.out.println(count);
}
public static void main(String[] args) {
find();
}
}
最佳答案
上述逻辑的解决方法是
String p = ".-.";
String s = "-.-.-.-";
int count = 0;
for (int index = s.indexOf(pa);
index >= 0;
index = s.indexOf(pa, index + 1)){
count++;
}
关于java - 为什么我的正则表达式找不到我的模式的所有实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58144581/