简体   繁体   English

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

[英]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.

相关问题 Java使用子字符串函数的索引在两个字符之间的字符串中替换字符 - Java replace a character in a string between two characters using the indexes from the substring function 如何替换不在两个字符之间的所有字符串? - How do you replace all strings that are not between two characters? 正则表达式-如何确保两个字符之间或从开始到特定字符仅出现一个字符实例 - Regex - How to make sure only 1 instance of character occuring between two characters or from start to certain character 正则表达式匹配和替换字符串之间的两个字符 - regex to match and replace two characters between string Java:如何用单个字符替换连续字符? - Java: How to replace consecutive characters with a single character? 如何用替换/正则表达式替换字符串中的两个字符? - How to replace two characters in a String with replace/regex? 替换Java中其他两个字符之间的字符串中的所有字符 - Replace all characters in a string that are between two other characters in Java 如何在Java中替换字符串的一部分,它匹配第一个字符,转义中间的一些字符并匹配最后的一些字符? - How to replace part of a string in Java, where it matches 1st few characters, escape some in between and matches some character at the end? java字符串替换两个不同特殊字符之间的空格 - java string replace whitespaces between two different special characters 使用正则表达式替换两个定界符之间的所有字符 - Replace all characters between two delimiters using regex
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM