正则表达式:在匹配模式后的字符串中插入 space

RegEx : Insert space in the string after a matched pattern

在 Java 中,我想在字符串后插入一个 space,但前提是该字符串包含 "MAVERICK"。我认为使用使用正则表达式作为参数的 replaceAll() 方法可以做到这一点,但我并没有真正理解它。

这是我的

String s = "MAVERICKA";
//the last character can be from the following set [A,Z,T,SE,EX]

所以,我希望该函数 return 我的字符串 "MAVERICK A" 或 "MAVERICK EX"。 例如

此外,如果字符串的格式已经正确,则不应插入 space。即

怎么样

s = s.replaceAll("MAVERICK(A|Z|T|SE|EX)", "MAVERICK ");

你的意思是这样的:

String r = s.replaceAll("(MAVERICK)([AZT]|SE|EX)", " ");

另一种不知道结尾字母的解决方案是:

String spaced_out = s.replaceAll("(MAVERICK)(?!\s|$)", " ");