1

I have a string stored in a variable which contains square brackets. I want to use this string as part of a regex statement, and have found I need to double escape the square brackets to get the result I need.

The string is of the form:

String str = "myVar[100]";

and the regex is used to parse a text file and look for the value between quotes after this string, i.e. the value of the variable:

if(str.contains("[")) {
  str.replace("[", "\\\\[");
  str.replace("]", "\\\\]");
}

Regex:

Pattern q = Pattern.compile(str + " *?= *?\"(.*)\";");   
Matcher n = q.matcher(line);
while (n.find()) {
  System.out.println(n.group(0));
}

But it's not finding any matches. Am I escaping the backslashes correctly?

  • 4
    Don't build the escaping yourself, use https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#quote(java.lang.String) – Robert Jan 10 '17 at 22:25
  • You don't want to escape a slash, right? – Roman C Jan 10 '17 at 22:27
  • @RomanC right, i want to insert two backslashes before the brackets. Per Roberts comment above, may not need to do it at all? –  Jan 10 '17 at 22:28
  • @Robert it works! put that as an answer and i'll mark it as such. you've no idea how long ive been wrangling with this. So simple, classic! –  Jan 10 '17 at 22:32

0 Answers0