【问题标题】:Java regex to match for variable valueJava 正则表达式匹配变量值
【发布时间】:2017-01-09 22:01:25
【问题描述】:

我希望在我正在解析的包含代码的文本文件中提取特定变量的值。变量名称发生了变化,它在代码中的位置也发生了变化,但我知道模式,因此我成功获取了它的值并将其存储在一个名为 myVar 的变量中。

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

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

但是编译的时候报错:

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

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

【问题讨论】:

  • 运行时变量myVar中有什么?
  • @Asaph variable_name[2]形式的字符串

标签: java regex


【解决方案1】:

\= 不是转义序列。 您可能需要转义 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

【讨论】:

  • @Xlsx 是对的。将\= 更改为=\\=(如果您真的想要其中的前导反斜杠,尽管没有任何意义)。
  • \= 的问题根本不是正则表达式问题。 \= 在 Java 字符串中无效。它甚至没有编译正则表达式,因为 java 代码甚至没有编译。
  • 好的,删除反斜杠并编译,但不返回组中的任何值,所以一定有另一个问题。谢谢。我会继续检查的。
  • 你可能还需要在引号前添加另一个反斜杠,因为 java 将 \" 识别为只有 ",你应该写 \\"
猜你喜欢
  • 2015-07-06
  • 1970-01-01
  • 2018-08-12
  • 1970-01-01
  • 1970-01-01
  • 2011-03-30
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多