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 なしでテストしたため、\and"が誤ってエスケープされる可能性があります。

http://regexr.com?303mm

于 2012-02-23T00:32:23.737 に答える
0

The pattern

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

Seems to do what you want. Here's the escaped version for Java:

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

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.

于 2012-02-23T00:43:53.370 に答える