user2672288
user2672288

Reputation:

Java regex to match for variable value

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?

Upvotes: 0

Views: 2070

Answers (1)

XMB5
XMB5

Reputation: 1602

\= 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

Upvotes: 2

Related Questions