[英]How to replace character between two characters?
I have strings "ABC DE", "ABC FE", "ABC RE". 我有字符串“ ABC DE”,“ ABC FE”,“ ABC RE”。
How to replace the characters between ABC and E using regex? 如何使用正则表达式替换ABC和E之间的字符?
Trying to do this with a regex and replace 尝试使用正则表达式替换
str.replace((ABC )[^*](E), 'G');
If you want to remove any characters that appear between "ABC " and "E", then you could accomplish this via lookaheads and the replaceAll()
method : 如果要删除出现在“ ABC”和“ E”之间的任何字符,则可以通过lookaheads和replaceAll()
方法完成此操作:
String[] strings = { "ABC DE", "ABC FE", "ABC RE" };
for(int s = 0; s < strings.length; s++){
// Update each string, replacing these characters with a G
strings[s] = strings[s].replaceAll("(?<=ABC ).*(?=E)","G"));
}
Likewise if you didn't explicitly want the space after "ABC", simply remove it from the lookahead by using (?<=ABC).*(?=E)
. 同样,如果您不明确希望在“ ABC”之后留空格,则只需使用(?<=ABC).*(?=E)
将其从前行中删除。
You can see an interactive example of this here . 您可以在此处看到一个交互式示例 。
You probably want to use regex replaceAll
with "ABC(.*?)E"
instead. 您可能要使用带有"ABC(.*?)E"
正则表达式replaceAll
。
str = str.replaceAll("ABC(.*?)E", "G");
Explanation: 说明:
ABC matches the characters ABC literally (case sensitive)
1st Capturing group (.*?)
.*? matches any character (except newline)
Quantifier: *? Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
E matches the character E literally (case sensitive)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.