0

I'm looking to extract the value of a particular variable in a text file that I'm parsing containing code. The variable name changes, as does its position in the code, but I know the pattern therefore I successfully obtain its value and store it in a variable, called myVar.

To get the value, i.e. the string between quotes after the myVar and equals sign, i.e. myVar = "value i want is here" I thought about using regex as follows:

Pattern q = Pattern.compile(myVar + "\= \"(.*)\"" );

But I get an error when compiling:

error: illegal escape character Pattern q = Pattern.compile(myVar + "\= \"(.*)\"" );

Is this something to do with concatenating the myVar string with the regular expression?

2
  • What's in the variable myVar at runtime? Commented Jan 9, 2017 at 22:05
  • @Asaph a string of the form variable_name[2] Commented Jan 9, 2017 at 22:07

1 Answer 1

2

\= is not an escape sequence. You probably need to escape the Regex string for java. Here is a link for doing that: http://www.freeformatter.com/java-dotnet-escape.html

Escape Sequences
\t  Insert a tab in the text at this point.
\b  Insert a backspace in the text at this point.
\n  Insert a newline in the text at this point.
\r  Insert a carriage return in the text at this point.
\f  Insert a formfeed in the text at this point.
\'  Insert a single quote character in the text at this point.
\"  Insert a double quote character in the text at this point.
\\  Insert a backslash character in the text at this point.

From http://docs.oracle.com/javase/tutorial/java/data/characters.html

Sign up to request clarification or add additional context in comments.

4 Comments

@Xlsx is right. Change \= to either = or \\= (if you really want the leading backslash in there, although there isn't any point to having it).
The problem with \= is not a regex issue at all. \= isn't valid in a java String. It's not even getting as far as compiling the regex because the java code doesn't even compile.
ok, removed the backslash and it compiles, but doesnt return any value in the group, so must have another issue somewhere. thanks. i'll keep checking.
You probably also have to add another backslash to the ones before the quotes, because java recognizes \" as only ", you should write \\"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.