I have a very long regular expression that seems to be having issues, but only when imported from a text file. I've narrowed it down to the following section (shown here as a literal String):
"(?i)(?<!\\w)\\w{2,3}(?=\\))"
As you can see, near the end, I am trying to escape a closing parenthesis for a lookahead. Now, if this is hard-coded, like:
Pattern myPattern = Pattern.compile("(?i)(?<!\\w)\\w{2,3}(?=\\))");
It works completely as expected. If, however, I read it from a text file, like:
File patternFile = new File("patterns.txt");
List<String> patternText = FileUtils.readLines(patternFile);
String ucText = patternText.get(0).trim();
Pattern myPattern = Pattern.compile(ucText);
Then I get the error message:
Exception in thread "Thread-4" java.util.regex.PatternSyntaxException: Unmatched closing ')' near index 25
(?i)(?<!\\w)\\w{2,3}(?=\\))
^
So, why is this happening? Why is escaping a closing parenthesis legal when hard-coded, but not when reading from a text file?