[英]Regular expression to remove a substring between two strings
周圍也有類似的例子,但是我找不到解決方法
目標:刪除/ *和* /之間的所有(包括)數據。 我正在使用下面的代碼
String str="this /* asdasda */ is test";
str = str.replaceAll("/\\*.*?\\*/","") ;
System.out.println(str);
輸出:
this is test
這些嵌套時出現問題
String str="this /* asdas/* extra comments */da */ is test";
str = str.replaceAll("/\\*.*?\\*/","") ;
System.out.println(str);
產量
this da */ is test
我無法解決嵌套部分。 我需要它丟棄/ *和* /之間的任何內容
例如
"this /* asdas/* extra commen/* asdas */ ts */da */ is test /* asdas */ asdasd ";
應該翻譯成
this is test asdasd
將replaceAll
的正則表達式更改為/\\\\*.*\\\\*/
正在運行:
String str="this /* asdas/* extra comments */da */ is test";
str = str.replaceAll("/\\*.*\\*/","") ;
System.out.println(str);
輸出:
this is test
正在運行:
String str="hello /*/* asdas/* eer/* hemmllo*/ */da */ */world";
str = str.replaceAll("/\\*.*\\*/","") ;
System.out.println(str);
輸出:
hello world
假設您使用簡單的單詞,請嘗試以下操作:
replaceAll("(/\\*( *(\\w) *)*)|(( *(\\w) *)*\\*/)","").replaceAll("\\*/|/\\*","");
測試1:
String str="/* huhu /* jij */ /* */ here /* asfas /* kjk */ kh*/ here to";
str = str.replaceAll("(/\\*( *(\\w) *)*)|(( *(\\w) *)*\\*/)","").replaceAll("\\*/|/\\*","");
System.out.println(str);
輸出:
here here to
測試2:
String str1="this /* asdas/* extra commen/* asdas */ ts */da */ is test /* asdas */ asdasd ";
str1 = str1.replaceAll("(/\\*( *(\\w) *)*)|(( *(\\w) *)*\\*/)","").replaceAll("\\*/|/\\*","") ;
System.out.println(str1);
輸出:
this is test asdasd
測試3:
String str2="this /* /* i */ is /**/ */ test";
str2 = str2.replaceAll("(/\\*( *(\\w) *)*)|(( *(\\w) *)*\\*/)","").replaceAll("\\*/|/\\*","") ;
System.out.println(str2);
輸出:
this is test
Java不支持遞歸匹配,因此您將無法一次性完成它。 對於確實支持遞歸正則表達式匹配的語言,您可以嘗試如下操作:
(\\/\\*(?>[^\\/\\*\\*\\/]+|(?1))*\\*\\/)
要在Java中模擬遞歸匹配,可以在實際的正則表達式之外添加邏輯(執行多次)。
取出|(?1)
or
部分,您有
(\\/\\*(?>[^\\/\\*\\*\\/]+)*\\*\\/)
如果您像這樣使用模式匹配器:
String regex = "(\\/\\*(?>[^\\/\\*\\*\\/]+)*\\*\\/)";
String str="this /* asdas/* extra commen/* asdas */ ts */da */ is test /* asdas */ asdasd ";;
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while (m.find()) {
str = m.replaceFirst("");
m = p.matcher(str);
System.out.println(str);
}
// here your string is
// this is test asdasd
最后一遍將為您提供您要查找的字符串
請參閱https://regex101.com/在線試用正則表達式,我發現它很有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.