我正在尝试取一个字符串:
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;
}
谢谢大家。
答案 0 :(得分:3)
我喜欢已发布的两个答案,计算单词并减去一个,但如果您只需要一个正则表达式来查找重叠匹配:
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 :(得分:0)
从i = 0运行for循环到单词数 - 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]);
}
句子中的双字符串数量就是单词数减一。
int numOfWords = string.split(" ").length - 1;
答案 2 :(得分:0)
总对数=总字数 - 1
你已经知道如何计算单词总数。
答案 3 :(得分: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));
}
来自模式([^ ]+)( )([^ ]+)
........................... | _______________ |
..................................组(0)
.......................... | ([^ ]+)
| &LT; - 基团(1)
...................................... | ( )
| &LT; - 基团(2)
............................................ | ([^ ]+)
| &LT; - 基团(3)