从java代码中提取字符串的正则表达式
要匹配的示例源代码是从java代码中提取字符串的正则表达式,java,regex,Java,Regex,要匹配的示例源代码是 String string="welcome"; String k="a\"welcome"; 我正在java中使用“(\”[^(\”)]*\”regex 但是这个摘录 0:"welcome" 0:"a\" 预期产量为 0:"welcome" 0:"a\"welcome" 我应该在regex中做什么更改以获得预期的输出 Java源代码: private static String pattern1="(\"[^(\")]*\")"; public void getSt
String string="welcome";
String k="a\"welcome";
我正在java中使用“(\”[^(\”)]*\”
regex
但是这个摘录
0:"welcome"
0:"a\"
预期产量为
0:"welcome"
0:"a\"welcome"
我应该在regex中做什么更改以获得预期的输出
Java源代码:
private static String pattern1="(\"[^(\")]*\")";
public void getStrings(){
Pattern r = Pattern.compile(pattern1);
Matcher m = r.matcher("String string=\"welcome\";\n" +
"String k=\"a\\\"welcome\";");
while(m.find()){
System.out.println("0:"+m.group(0));
}
}
只需在正则表达式中使用lookahead和lookahead
(?<==)(".*?")(?=;)
或
使用贪婪的*
Pattern r = Pattern.compile("(\".*\")");
或
它跳过前面有反斜杠的双引号
Pattern r = Pattern.compile("(\\\".*?(?<=[^\\\\])\\\")");
Pattern r=Pattern.compile(“(\\\”*?(?为什么还要麻烦变量赋值。你知道”
中的所有内容都是字符串
“(.+)”\s*;
应该很好。你应该告诉我们什么模式不匹配,或者更好的是匹配与否的原则。你也可以尝试一下。它只跳过由反斜杠进行的双引号。或者这,(\“*?[^\\]\”
Pattern r = Pattern.compile("(\".*\")");
Pattern r = Pattern.compile("(\\\".*?(?<=[^\\\\])\\\")");