我有一個字符串,其中包含html代碼,並試圖將其中的不同URL的域名替換爲http://localhost
但我應用的正則表達式總是返回最後一個匹配而不是整個串。 請參考下面爲什麼java正則表達式replaceAll()只返回最後一個匹配
String data = "https://example.com/abc/xyz https://sub.example.com/abc/def https://sub-example.com/abc/ijk";
System.out.println(data);
data = data.replaceFirst("(http|https)://.*/abc/", "http://localhost/");
System.out.println(data);
下面的代碼片段被輸出這段代碼生成
http://localhost/ijk
我在做什麼錯在這裏...請讓我知道
'*'是貪婪的將最後一個'/ ABC /使用''之前匹配最長的字符串。*?' – anubhava
您有簡單地從第一HTTPS產生一個貪婪的匹配到你輸入的盡頭。 – GhostCat
使用'。*?'可以減少字符的貪婪 – Ferrybig