RegEx: put a space on the line after the matched pattern

In Java, I want to insert a space after the line, but only if the line contains "MAVERICK". I think using the replaceAll () method that uses regular expressions as a parameter will do it, but I really don't get 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 the string "MAVERICK A" or "MAVERICK EX" to me. Example.

  • 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
+3


source to share


3 answers


How about something like



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

      

+7


source


You mean something like this:



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

      

+2


source


Another solution, without knowing the final letters, would be this:

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

      

+2


source







All Articles