英文:
Regex max a string till " and not stop at \"
问题
我有一个需要用正则表达式检查的字符串:
"field":"Testing, for something \"and something\""
我想要进行模式匹配并替换为:
"field":"SAFE"
为此,我正在尝试进行模式匹配并捕获直到最后一个反引号。我尝试了以下正则表达式,但它不匹配:
Pattern p = Pattern.compile("\"field\":\".*?(?!\\\")\"");
对于正则表达式我还不熟悉,有人可以建议我可能做错了什么吗?谢谢!
编辑:
我想问题没有表述清楚。抱歉。上面的内容并不是字符串的结尾。它可以连续包含更多字段:
"field":"Testing, for something \"and something\"", "new_field":"blahblah", ...
输出应为:
"field":"SAFE", "new_field":"blahblah", ...
英文:
I have a String to be checked for regex :
"field":"Testing, for something \"and something\""
which I want to pattern match and replace with :
"field":"SAFE"
For this, I am trying to pattern match and capture till the last inverted commas. I have tried the following regex, but its not matching :
Pattern p = Pattern.compile("\"field\":\".*?(?!\\\")\"");
New to regex, can anyone suggest what I might be doing wrong? Thanks!
EDIT :
I guess the question was not clear. Apologies. The above is not the end of the string. It can contain more fields in succession :
"field":"Testing, for something \"and something\"", "new_field":"blahblah", ...
output should be :
"field":"SAFE", "new_field":"blahblah", ...
答案1
得分: 2
你可以按照以下方式进行操作:
public class Testing {
public static void main(String[] args) {
String str = "\"field\":\"Testing, for something \\\"and something\\\"\"";
str = str.replaceAll("(\"field\":).*", "$1\"SAFE\"");
System.out.println(str);
}
}
输出:
"field":"SAFE"
解释:
(\"field\":)
是第一个捕获组。.*
匹配所有字符。$1
代表第一个捕获组。
更新:
根据问题提供者的澄清,可以使用正向先行断言来匹配逗号,如下所示:
public class Testing {
public static void main(String[] args) {
String str = "\"field\":\"Testing, for something \\\"and something\\\"\", \"new_field\":\"blahblah\"";
str = str.replaceAll("(\"field\":).*(?=,)", "$1\"SAFE\"");
System.out.println(str);
}
}
输出:
"field":"SAFE", "new_field":"blahblah"
英文:
You can do it as follows:
public class Testing {
public static void main(String[] args) {
String str = "\"field\":\"Testing, for something \\\"and something\\\"\"";
str = str.replaceAll("(\"field\":).*", "$1\"SAFE\"");
System.out.println(str);
}
}
Output:
"field":"SAFE"
Explanation:
(\"field\":)
is the first capturing group.*
specifies all characters$1
specifies the first capturing group
Update:
Writing this update based on the clarification from OP.
You can use positive lookahead for comma as shown below:
public class Testing {
public static void main(String[] args) {
String str = "\"field\":\"Testing, for something \\\"and something\\\"\", \"new_field\":\"blahblah\"";
str = str.replaceAll("(\"field\":).*(?=,)", "$1\"SAFE\"");
System.out.println(str);
}
}
Output:
"field":"SAFE", "new_field":"blahblah"
答案2
得分: 0
这里是一个示例。
$str = ''"field":"Testing, for something \"and something\""'';
echo preg_replace('/(\"field\":\")(.*)(\")/i', "$1SAFE$3", $str);
正则表达式已在此处进行了测试:这里。
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论