java - 正则表达式删除两个字符串之间的子字符串

标签 java regex

周围有类似的例子,但我找不到我的解决方案

目的:删除/*和*/之间的所有(包括)数据。我正在使用下面的代码

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/

相关文章:

java - Java 中的模幂运算

mysql - 如何在MySQL中使用REGEXP获取特定列

java - 从不包括非拉丁字符的字符串中删除所有特殊字符

java - 从Java中的Path获取规范路径

java - 如何在java中的正则表达式模式末尾分割字符串

c# - "111 -> c:\my source\file1.cpp (no code)"的正则表达式 (C#)

c# - 在大字符串中查找标记

Java - Rome rss 阅读器?

java - Spring Social Twitter - 提及帐户时通知应用程序

java - 无法连接到hive server2(SQL异常、thrift传输异常等)