【问题标题】:Matcher not finding overlapping words?匹配器没有找到重叠的单词?
【发布时间】:2012-09-18 05:32:47
【问题描述】:

我正在尝试取一个字符串:

String s = "This is a String!";

并返回该字符串中的所有 2 字对。即:

{"this is", "is a", "a String"}

但现在,我能做的就是返回:

{"this is", "a String"}

如何定义我的 while 循环,以便我可以解释这种缺少重叠词的情况?我的代码如下:(真的,我很高兴它只返回一个表示它找到多少个字符串子集的 int ......)

int count = 0;
while(matcher.find()) {
    count += 1;
}

谢谢大家。

【问题讨论】:

标签: java overlapping matcher


【解决方案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 更聪明一点,因为在“the force”上尝试此操作将匹配“he force”然后是“e force”。当然,这对于计算单词来说是多余的,但如果正则表达式比这更复杂,这可能会很有用。

【讨论】:

    【解决方案2】:

    从 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]);
    }
    

    一个句子中两词串的数量就是词数减一。

    int numOfWords = string.split(" ").length - 1;
    

    【讨论】:

      【解决方案3】:

      总对数 = 总字数 - 1

      而且你已经知道如何计算总字数了。

      【讨论】:

        【解决方案4】:

        我尝试了一组模式。

        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)
        ......................|([^ ]+)| .............................|( )| ..............................|([^ ]+)|

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-08-29
          • 2011-08-02
          • 2014-09-15
          • 1970-01-01
          • 2017-05-25
          相关资源
          最近更新 更多