周围有类似的例子,但我找不到我的解决方案
目的:删除/*和*/之间的所有(包括)数据。我正在使用下面的代码
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 - 正则表达式删除两个字符串之间的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48796366/