Pattern.compile()抛出异常

时间:2014-06-20 10:51:37

标签: java android regex string pattern-matching

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

    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附近的regexp模式中嵌套的括号不正确: \湾{0}(1110R。{0}。 \ B'/ p>

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

1 个答案:

答案 0 :(得分:1)

尝试引用searchText String

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

...因为它可能包含Pattern个保留字符,因此会破坏您的Pattern

编辑 ...包含非闭合括号时就是这种情况。

编辑(II)

不确定您要使用".*\\b.{0}"的{​​{1}}部分尝试完成的工作。

在这种情况下,这是两个有效的例子:

  • 用于文字匹配(Pattern应执行相同的操作)
  • 用于非字边界匹配,其中给定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的初始化标记。