Search code examples
javaregexreplaceall

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. i.e

  • MAVERICK A -> MAVERICK A

Solution

  • How about something like

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