简体   繁体   中英

RegEx : Insert space in the string after a matched pattern

In Java I want to insert a space after a string but only if the string contains "MAVERICK". I think using replaceAll() method which uses regular expressions as a parameter will do it, but i am not really getting it.

Here is what i have

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

So, i want the function to return me the string "MAVERICK A" or "MAVERICK EX". Ex.

  • MAVERICKA -> MAVERICK A
  • MAVERICKEX -> MAVERICK EX

Also, if the string is already in the correct format it should not insert a space. ie

  • MAVERICK A -> MAVERICK A

怎么样的

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

另一个不知道尾随字母的解决方案是:

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

你的意思是这样的:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM