匹配器找不到重叠的单词?
我正在尝试取一个字符串:
String s = "This is a String!";
并返回该字符串中的所有双字对。 即:
{"this is", "is a", "a String"}
但是现在,我能做的就是返回:
{"this is", "a String"}
如何定义我的while循环,以便我可以解释这个重叠单词的缺失? 我的代码如下:(真的,我很高兴它只返回一个int,表示它找到了多少个字符串子集……)
int count = 0; while(matcher.find()) { count += 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更聪明,因为在“力量”上尝试这个将匹配“他力”然后“e力”。 当然,这对于计算单词来说是过度的,但如果正则表达式比这更复杂,这可能会有用。
总对数=总字数 – 1
而且你已经知道如何计算单词的总数。
从i = 0运行for循环到单词数 – 2,然后单词i和i + 1将组成单个双字串。
String[] splitString = string.split(" "); for(int i = 0; i < splitString.length - 1; i++) { System.out.println(splitString[i] + " " + splitString[i+1]); }
句子中的2个字符串的数量就是单词的数量减1。
int numOfWords = string.split(" ").length - 1;
我尝试了一组模式。
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)); }
从模式([^ ]+)( )([^ ]+)
……………………… | _______________ |
…………………………….组(0)
…………………….. | ([^ ]+)
| < - 基团(1)
……………………………….. | ( )
| < - 基团(2)
…………………………………….. | ([^ ]+)
| < - 基团(3)