繁体   English   中英

Pattern.compile()引发异常

[英]Pattern.compile() throws exception

我正在使用正则表达式来查找书页中是否存在字符串。 下面是相同的代码。

    String regex = ".*\\b.{0}" + searchText + ".{0}.*\\b";
    Pattern pattern = Pattern.compile(regex);
    pattern.matcher("This is the text area where I am trying to look for the particular text, which is in the variable searchText. This text will have the string (222M) as part of this string. The find method should give me a true result even if I don't enter the closing brakect of the word. This is a multiline string").find()

观察:

  • 情况1:当searchText =“(222M)”
  • 结果:找到该字符串。

  • 情况2:当searchText =“(222M” // //缺少括号时

    我得到以下异常。

    在索引22附近的正则表达式模式中嵌套的括号不正确。 \\ b。{0}(1110r。{0}。 \\ b

还有一种在页面中查找字符串的更好的选择。 使用String.contains()不一致。 这是在android平台上。 ^

尝试引用searchText String

... + Pattern.quote(searchText) + ...

...,因为它可能包含Pattern保留字符,从而破坏了Pattern

编辑 ...,当它包含非封闭的括号时就是这种情况。

编辑(II)

不太确定要使用Pattern".*\\\\b.{0}"部分来完成什么。

在这种情况下,有两个工作示例:

  • 用于文字匹配( String.contains应该执行相同的操作)
  • 用于非单词限制的匹配,其中给定String之前或之后的任何字符都是非单词字符

     String searchText = "(222M"; String regex = Pattern.quote(searchText); Pattern pattern = Pattern.compile(regex); Pattern boundedPattern = Pattern.compile("(?<=\\\\W)" + regex + "(?=\\\\W)"); String input = "This is the text area where I am trying " + "to look for the particular text, which is in the variable searchText. " + "This text will have the string (222M) as part of this string. " + "The find method should give me a true result even if I don't " + "enter the closing brakect of the word. This is a multiline string"; Matcher simple = pattern.matcher(input); Matcher bounded = boundedPattern.matcher(input); if (simple.find()) { System.out.println(simple.group()); } if (bounded.find()) { System.out.println(bounded.group()); } 

产量

(222M
(222M

最后说明

如果希望它们不区分大小写,则可以将Pattern.CASE_INSENSITIVE作为初始化标志添加到您的Pattern

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM