Java 替换/删除两个字符之间的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3756657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 04:28:16  来源:igfitidea点击:

Replace/remove String between two character

javastring

提问by Jimmy

I want to remove a string that is between two characters and also the characters itself , lets say for example:

我想删除两个字符之间的字符串以及字符本身,例如:

i want to replace all the occurrence of the string between "#?" and ";" and remove it with the characters.

我想替换“#?”之间出现的所有字符串 和 ”;” 并将其与字符一起删除。

From this

由此

"this #?anystring; is  #?anystring2jk; test"
"this #?anystring; is  #?anystring2jk; test"

To This

至此

"this is test"
"this is test"

how could i do it in java ?

我怎么能在java中做到这一点?

采纳答案by Computerish

Use regex:

使用正则表达式:

myString.replaceAll("#\?.*?;", "");

回答by Carl

string.replaceAll(start+".*"+end, "")

string.replaceAll(start+".*"+end, "")

is the easy starting point. You might have to deal with greedinessof the regex operators, however.

是简单的起点。但是,您可能不得不处理正则表达式运算符的贪婪问题。

回答by A_Var

@computerish your answer executes with errors in Java. The modified version works.

@computerish 你的答案在 Java 中执行时出错。修改后的版本有效。

myString.replaceAll("#\?.*?;", "");

The reason being the ? should be escaped by 2 backslashes else the JVM compiler throws a runtime error illegal escape character. You escape ? characters using the backslash .However, the backslash character() is itself a special character, so you need to escape it as well with another backslash.

原因是?应该用 2 个反斜杠转义,否则 JVM 编译器会抛出运行时错误非法转义字符你逃吗?使用反斜杠的字符。但是,反斜杠 character() 本身是一个特殊字符,因此您还需要使用另一个反斜杠对其进行转义。