如何替换两个字符之间的字符?

时间:2016-05-13 16:58:45

标签: java regex

我有字符串" ABC DE"," ABC FE"," ABC RE"。

如何使用正则表达式替换ABC和E之间的字符?

尝试使用正则表达式执行此操作并替换

str.replace((ABC )[^*](E), 'G');

2 个答案:

答案 0 :(得分:0)

如果要删除“ABC”和“E”之间出现的任何字符,则可以通过前瞻和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"));
}

同样,如果您没有明确地想要“ABC”之后的空格,只需使用(?<=ABC).*(?=E)将其从前瞻中移除。

你可以see an interactive example of this here

答案 1 :(得分:-1)

您可能希望将正则表达式replaceAll改为使用"ABC(.*?)E"

str = str.replaceAll("ABC(.*?)E", "G");

说明:

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)