2017-01-09 6 views
0

私は、コードを含む解析中のテキストファイル内の特定の変数の値を抽出します。変数名はコード内の位置と同様に変化しますが、パターンを知っているので、その値を正常に取得して変数myVarに格納します。変数の値と一致するJava正規表現

値を取得するには、myVarを後に引用符の間の文字列をIEと等号、すなわちmyVar = "value i want is here"私は次のように正規表現を使用して考えた:

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

しかし、コンパイルするとき、私はエラーを取得する:

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

これは、myVar文字列を正規表現と連結することと関係がありますか?

+0

から、実行時に変数 'myVar'には何が? – Asaph

+0

@Asaph 'variable_name [2]'の形式の文字列 –

答えて

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

+1

@Xlsxが正しいです。 '\ ='を '='または '\\ ='に変更します(もしそこに先行するバックスラッシュが本当に必要な場合は、そこには何のポイントもありません)。 – Asaph

+0

'\ ='の問題は正規表現の問題ではありません。 '\ ='はjava文字列では無効です。 Javaコードがコンパイルされないので、正規表現をコンパイルすることさえできません。 – Asaph

+0

OK、バックスラッシュを削除してコンパイルしましたが、グループ内の値を返さないため、別の問題がどこかにあるはずです。ありがとう。私はチェックを続けます。 –

関連する問題