Java正则表达式匹配变量值

时间:2017-01-09 22:01:26

标签: java regex

我正在寻找在我正在解析包含代码的文本文件中提取特定变量的值。变量名称的变化,以及它在代码中的位置,但我知道模式,因此我成功获取其值并将其存储在名为myVar的变量中。

要获取值,即myVar和等号后面的引号之间的字符串,即myVar = "value i want is here"我考虑使用正则表达式,如下所示:

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

但是我在编译时遇到错误:

  

错误:非法转义字符   模式q = Pattern.compile(myVar +“\ = \”(。*)\“”);

这与将myVar字符串与正则表达式连接有关吗?

1 个答案:

答案 0 :(得分:2)

\=不是转义序列。 您可能需要转义java的Regex字符串。这是一个链接: 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.

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