Java Matcher找不到重叠的单词?
我试着用一根绳子:Java Matcher找不到重叠的单词?,java,overlapping,matcher,Java,Overlapping,Matcher,我试着用一根绳子: String s = "This is a String!"; 并返回该字符串中的所有2字对。即: {"this is", "is a", "a String"} 但现在,我所能做的就是返回: {"this is", "a String"} 我如何定义我的while循环,这样我就可以解释为什么没有重叠的单词了?我的代码如下:(真的,我很高兴它只返回一个int,表示它找到了多少个字符串子集…) 谢谢大家。运行一个for循环,从i=0到单词数-2,然后单词i和i+1将组成一
String s = "This is a String!";
并返回该字符串中的所有2字对。即:
{"this is", "is a", "a String"}
但现在,我所能做的就是返回:
{"this is", "a String"}
我如何定义我的while循环,这样我就可以解释为什么没有重叠的单词了?我的代码如下:(真的,我很高兴它只返回一个int,表示它找到了多少个字符串子集…)
谢谢大家。运行一个for循环,从i=0到单词数-2,然后单词i和i+1将组成一个2字字符串
String[] splitString = string.split(" ");
for(int i = 0; i < splitString.length - 1; i++) {
System.out.println(splitString[i] + " " + splitString[i+1]);
}
从i=0到单词数-2运行for循环,然后单词i和i+1将组成一个2字字符串
String[] splitString = string.split(" ");
for(int i = 0; i < splitString.length - 1; i++) {
System.out.println(splitString[i] + " " + splitString[i+1]);
}
总对数=总字数-1
您已经知道如何计算单词总数。总对数=单词总数-1
你已经知道如何计算单词总数。我喜欢已经发布的两个答案,计算单词数,减去一个,但是如果你只需要一个正则表达式来查找重叠的匹配项:
Pattern pattern = Pattern.compile('\\S+ \\S+');
Matcher matcher = pattern.matcher(inputString);
int matchCount = 0;
boolean found = matcher.find();
while (found) {
matchCount += 1;
// search starting after the last match began
found = matcher.find(matcher.start() + 1);
}
事实上,你需要比简单地加1聪明一点,因为在“原力”上尝试这个会匹配“he force”,然后是“e force”。当然,这对于计算单词来说是过分的,但是如果正则表达式比这更复杂,这可能会证明是有用的。我喜欢已经发布的两个答案,计算单词和减去一个,但是如果您只需要正则表达式来查找重叠的匹配:
Pattern pattern = Pattern.compile('\\S+ \\S+');
Matcher matcher = pattern.matcher(inputString);
int matchCount = 0;
boolean found = matcher.find();
while (found) {
matchCount += 1;
// search starting after the last match began
found = matcher.find(matcher.start() + 1);
}
事实上,你需要比简单地加1聪明一点,因为在“原力”上尝试这个会匹配“he force”,然后是“e force”。当然,这对于计算单词来说是过分的,但是如果正则表达式比它复杂的话,这可能会被证明是有用的。我尝试了使用模式组
String s = "this is a String";
Pattern pat = Pattern.compile("([^ ]+)( )([^ ]+)");
Matcher mat = pat.matcher(s);
boolean check = mat.find();
while(check){
System.out.println(mat.group());
check = matPOS.find(mat.start(3));
}
从模式([^]+)()([^]+)
………..|uuuuuuuuuuuuuuuuuuuuuuuu124;
组(0)
我尝试了一组模式
String s = "this is a String";
Pattern pat = Pattern.compile("([^ ]+)( )([^ ]+)");
Matcher mat = pat.matcher(s);
boolean check = mat.find();
while(check){
System.out.println(mat.group());
check = matPOS.find(mat.start(3));
}
从模式([^]+)()([^]+)
………..|uuuuuuuuuuuuuuuuuuuuuuuu124;
组(0)
你看到了吗?你看到了吗?