0

需要找到以下问题的表达式:

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 favourite hobby?\",\"answer\" :\"*******\"},{ \"questionID\" :\"5\", \"question\" :\"What was the name of the first company you worked at?\",\"answer\" :\"******\"}";

我正在尝试什么:

    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\" :\"******\"}";

由于贪婪的行为,第一组捕获了两个“答案”部分,而我希望它在找到足够的内容后停止,执行替换,然后继续寻找。

4

2 回答 2

0

以下正则表达式对我有用:

regex = "(?<=answer\"\\s:\")(answer.*?)(?=\"})";
rep = "*****";
replaceALL(regex,rep);

\"可能被错误地转义,因为我在没有 java的情况下进行了测试。

http://regexr.com?303mm

于 2012-02-23T00:32:23.737 回答
0

图案

("answer"\s*:\s*")(.*?)(")

似乎做你想做的事。这是 Java 的转义版本:

(\"answer\"\\s*:\\s*\")(.*?)(\")

这里的关键是用来(.*?)匹配答案而不是(.*)。后者匹配尽可能多的字符,前者会尽快停止。

如果答案中有双引号,上述模式将不起作用。这是一个允许他们使用的更复杂的版本:

("answer"\s*:\s*")((.*?)[^\\])?(")

您必须在替换模式中使用$4而不是。$3

于 2012-02-23T00:43:53.370 回答