需要找到以下問題的表達式: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 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\" :\"******\"}";
由於貪婪的行爲,第一組捕捉到兩個「答案」部分,而我希望它在找到足夠的部分後停下來,執行替換,然後繼續往前看。
我不明白這個問題。你有沒有*看過Java'Pattern'類? – 2012-02-23 00:24:03
我現在無法測試,但你可以嘗試'(\「answer \」\\ s *:\\ s * \「)(。*?)(\」)' – ARRG 2012-02-23 00:29:50
我確實是先生,我相信replaceAll會在內部使用Pattern.compile。基本上問題出在我的正則表達式中 - 我需要它來代替「答案」和「}」之間的所有文本,但由於它的貪婪性,它比我想要的要多得多。 IE瀏覽器。在我的「給定」字符串中,我希望字符87到95替換爲星號,字符210到218替換爲星號 - 但此刻只有第二次替換髮生,因爲第一個被認爲是第一組的一部分(由於貪婪行爲)。 – Konstantin 2012-02-23 00:32:08