【问题标题】:Setting up Matcher for String phrase that may include special characters as literals为可能包含特殊字符作为文字的字符串短语设置匹配器
【发布时间】:2011-07-16 09:35:13
【问题描述】:

无法确定如何将短语字符串与文件流中的短语匹配。我正在处理的文件包含随机单词,例如:

3 little pigs built houses and 1 little pig went to the market

等等。对于许多行。模式字符串中可能有特殊字符,例如V++ **A,所以我需要LITERAL 标志,以便可以找到它们,而不是在正则表达式中具有特殊含义。

我的模式是pattern = Pattern.compile(searchString, Pattern.LITERAL);

使用“little pig”作为我的模式字符串和matcher.find(),我可以找到两个匹配项:“小猪”和“小猪”。但是,我只希望它匹配“小猪”。

我能做什么?我考虑过使用matcher.lookingAt()matcher.matches(),但是当我不能依赖我匹配的文件字符串短语位于单独的行时,我不知道如何设置适当的区域。

【问题讨论】:

    标签: java regex file search matcher


    【解决方案1】:

    “小猪”是否经常被空格或换行等任何其他字符终止?然后你可以将它添加到模式中。

    String pattern = "(little pig)[ \\r\\n]+";
    

    【讨论】:

    • 这是否与 Pattern.LITERAL 冲突? (允许用户使用“C++”作为模式)例如。模式 = Pattern.compile(searchString, Pattern.LITERAL);如果没有,好主意!
    【解决方案2】:

    这个模式如何匹配包含字符串little pig 的任何行只匹配一次:

    ^.*little pig.*$
    

    其中包含:

    • ^ 行首
    • .* 零个或多个字符
    • $ 行尾

    【讨论】:

      【解决方案3】:
      String poet = "3 little pigs built houses and 1 little pig went to the market";
      Pattern p = Pattern.compile("(little pig)\\B");
      Matcher m = p.matcher(poet);
      List<String> idx = new ArrayList<String>();
      idx.add(m.group());
      System.out.println(idx);
      

      【讨论】:

        【解决方案4】:

        编辑 4(最后一个):完全忘记一开始需要 \\s|^

        编辑 3:做了一些调整以考虑到 searchString 之后的字符可能是字符串结尾 search P = Pattern.compile("\\s"+Pattern.quote(searchString)+"(\\s|$)");

        编辑 2:好的,我明白了! searchP = Pattern.compile("\\s"+Pattern.quote(searchString)+"\\s");

        不知道为什么我没有注意到引用方法...哦,第一次做所有事情:)

        编辑:结果证明我超前了 - 代码对特殊字符根本没有帮助,因为 literalP 在 searchP 中转换为 String 并且丢失了用户 String 的 LITERAL 规则。

        我想我明白了!下面将用户的字符串转换为文字,然后将其置于允许\\s 的新模式中。不过,如果有人发现它有问题,请告诉我。

        Pattern literalP = Pattern.compile(searchString, Pattern.LITERAL);
        Pattern searchP = Pattern.compile("\\s"+literalPattern+"\\s+");
        

        【讨论】:

          猜你喜欢
          • 2020-12-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-09-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-02
          相关资源
          最近更新 更多