【问题标题】:Find Text Between words in Java在 Java 中查找单词之间的文本
【发布时间】:2013-04-04 13:24:29
【问题描述】:

我想获取 2 个单词之间的所有文本(第一个单词是固定的 [One] 但第二个是 2 个单词 [Two] 或 [Three] 中的一个)。

注意 :: 找到的文本和第二个单词之间可能有也可能没有空格。 例如:

One     i am  
here
Two
i am fine 
One     i am 
here 
 Two
i am fine 
One     i am  
here
Three
i am fine 
One     i am  
here 
 Two
i am fine

我发现的是

Pattern p = Pattern.compile("(?<=\\bOne\\b)(.*?)(?=\\bTwo\\b)");

但这不正确,因为它需要完整的单词。

“二”有效。
“fineTwo”无效。

【问题讨论】:

  • 您的后视操作似乎无效。试试看:(?&lt;=One)(.*?)(?=\\b(?:Two|Three)\\b)

标签: java regex search


【解决方案1】:

它只匹配完整的单词,因为您使用单词边界\b。如果要接受“fineTwo”,则删除第一个边界

Pattern p = Pattern.compile("(?<=\\bOne\\b)(.*?)(?=Two\\b)");

要接受“二”或“三”作为结尾,请使用交替:

Pattern p = Pattern.compile("(?<=\\bOne\\b)(.*?)(?=(?:Two|Three)\\b)");

【讨论】:

    【解决方案2】:

    getTextBetweenTwoWords 方法可能有效。

    public static void main(String[] args)
    {
        String firstWord = "One";
        String secondword = "Two";
        String text = "One Naber LanTwo";
        System.out.println(getTextBetweenTwoWords(firstWord, secondword, text));
    }
    private static String getTextBetweenTwoWords(String firstWord, String secondword, String text)
    {
        return text.substring(text.indexOf(firstWord) + firstWord.length(), text.indexOf(secondword));
    }
    

    【讨论】:

      【解决方案3】:

      试试这个:

      for(String parseOne : Input.split("One"))
        for (String parseTwo : parseOne.split("Two"))
          for (String parseThree : parseTwo.split("Three"))
             System.out.println(parseThree.replace("One", "").replace("Two", "").replace("Three", "").trim());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-05
        • 2018-10-29
        • 1970-01-01
        • 2015-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-07
        相关资源
        最近更新 更多