Pattern.compile() throws exception

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-12 04:56:33

问题


I am using a regex to find if a string is present in a book page. Below is the code for the same.

    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()

Observations:

  • Case 1: when searchText = "(222M)"
  • Result: The string is found.

  • Case 2: when searchText = "(222M" // bracket missing

    I get the below exception.

    Incorrectly nested parentheses in regexp pattern near index 22: .\b.{0}(1110r.{0}.\b

Also is there a better option of finding the string in the page. Using String.contains() was inconsistent. This is on android platform. ^


回答1:


Try quoting the searchText String:

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

... as it might contain Pattern reserved characters, thus breaking your Pattern.

Edit ... which is the case when it contains a non-closed parenthesis.

Edit (II)

Not really sure what you are trying to accomplish with the ".*\\b.{0}" parts of your Pattern.

Here are two working example in that case:

  • for literal matching (String.contains should perform the same)
  • for non-word-bounded matching, wherein any character preceding or following the given String is a non-word character

    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());
    }
    

Output

(222M
(222M

Final note

You can add Pattern.CASE_INSENSITIVE as an initialization flag to your Pattern(s) if you want them to be case insensitive.



来源:https://stackoverflow.com/questions/24325598/pattern-compile-throws-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!