Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 368
Maverick Avatar asked Dec 19 '22 02:12

Maverick


2 Answers

How about something like

s = s.replaceAll("MAVERICK(A|Z|T|SE|EX)", "MAVERICK $1");
like image 167
Pshemo Avatar answered Jan 04 '23 22:01

Pshemo


Another solution without knowing the trailing letters would be:

String spaced_out = s.replaceAll("(MAVERICK)(?!\s|$)", "$1 ");
like image 40
Aarjav Avatar answered Jan 04 '23 22:01

Aarjav