簡體   English   中英

正則表達式用引號替換字符串

[英]Regex to replace string with quotes

我需要替換以下字符串中的引號。

String str = "This is 'test()ing' and test()ing'";

最終輸出應為“ This is test()ing and test()ing'”;

也就是說,僅當它以'test()開始並以'結尾時才替換。 中間的文字保持不變。

這個不起作用。

str = str.replaceAll("^('test())(.*)(')$", "test()$2");

請為此建議合適的正則表達式。

這個正則表達式將具有所需的結果:

    str = str.replaceAll("'test\\(\\)(.*?)'", "test()$1");

.*? 字符串是懶惰匹配的,與整個字符串的末尾不匹配。

看起來你真的不希望你的正則表達式中有^$ anchors(行的開頭/結尾)。

除此之外,它將消耗比您想要的更多的東西。 如果希望.* 盡早停止,可以繼續,則應勉強匹配,例如.*?

所以你的正則表達式是:

('test\(\))(.*?)(')

您可以使用:

str = str.replaceAll("'(test\\(\\)[^']*)'", "$1");

RegEx演示

使中間部分不貪心:

(')(.*?)(')

str = str.replaceAll("(')(.*?)(')", "$2");

如果它應該始終以test()開頭,請添加

str = str.replaceAll("(')(test().*?)(')", "$2");

檢查這個例子 ,這一個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM