问题
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.containsshould perform the same) for non-word-bounded matching, wherein any character preceding or following the given
Stringis a non-word characterString 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