java正则表达式用于勉强匹配
需要找到以下问题的表达式:
String given = "{ \"questionID\" :\"4\", \"question\":\"What is your favourite hobby?\",\"answer\" :\"answer 4\"},{ \"questionID\" :\"5\", \"question\" :\"What was the name of the first company you worked at?\",\"answer\" :\"answer 5\"}";
我想要得到什么: "{ \"questionID\" :\"4\", \"question\":\"What is your favorite hobby?\", \"answer\" :\"********\"},{ \"questionID\" :\"5\", \"question\" :\"您工作的第一家公司的名称是什么在?\",\"回答\" :\"*****\"}";
我正在尝试什么:
String regex = "(.*answer\"\\s:\"){1}(.*)(\"[\\s}]?)";
String rep = "$1*****$3";
System.out.println(test.replaceAll(regex, rep));
我得到什么:
"{ \"questionID\" :\"4\", \"question\":\"What is your favourite hobby?\",\"answer\" :\"answer 4\"},{ \"questionID\" :\"5\", \"question\" :\"What was the name of the first company you worked at?\",\"answer\" :\"******\"}";
由于贪婪的行为,第一组捕获了两个“答案”部分,而我希望它停止找到足够的后,进行替换,然后继续进一步查找。
need to find an expression for the following problem:
String given = "{ \"questionID\" :\"4\", \"question\":\"What is your favourite hobby?\",\"answer\" :\"answer 4\"},{ \"questionID\" :\"5\", \"question\" :\"What was the name of the first company you worked at?\",\"answer\" :\"answer 5\"}";
What I want to get: "{ \"questionID\" :\"4\", \"question\":\"What is your favourite hobby?\",\"answer\" :\"*******\"},{ \"questionID\" :\"5\", \"question\" :\"What was the name of the first company you worked at?\",\"answer\" :\"******\"}";
What I am trying:
String regex = "(.*answer\"\\s:\"){1}(.*)(\"[\\s}]?)";
String rep = "$1*****$3";
System.out.println(test.replaceAll(regex, rep));
What I am getting:
"{ \"questionID\" :\"4\", \"question\":\"What is your favourite hobby?\",\"answer\" :\"answer 4\"},{ \"questionID\" :\"5\", \"question\" :\"What was the name of the first company you worked at?\",\"answer\" :\"******\"}";
Because of the greedy behaviour, the first group catches both "answer" parts, whereas I want it to stop after finding enough, perform replacement, and then keep looking further.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该模式
似乎可以满足您的要求。这是 Java 的转义版本:
这里的关键是使用
(.*?)
来匹配答案,而不是(.*)
。后者匹配尽可能多的字符,前者会尽快停止。如果答案中有双引号,则上述模式将不起作用。这是一个更复杂的版本,将允许它们:
("answer"\s*:\s*")((.*?)[^\\])?(")
您将有在替换模式中使用
$4
代替$3
。The pattern
Seems to do what you want. Here's the escaped version for Java:
The key here is to use
(.*?)
to match the answer and not(.*)
. The latter matches as many characters as possible, the former will stop as soon as possible.The above pattern won't work if there are double quotes in the answer. Here's a more complex version that will allow them:
("answer"\s*:\s*")((.*?)[^\\])?(")
You'll have to use
$4
instead of$3
in the replacement pattern.以下正则表达式适用于我:
\
和"
可能会被错误地转义,因为我没有使用 java 进行测试。http://regexr.com?303mm
The following regex works for me :
The
\
and"
might be incorrectly escaped since I tested without java.http://regexr.com?303mm