javaregex

Remove space before specific substring


I think regex can help me here.

Lets say I have String What is foo. Where is foo. How is foo. Why foo? When foo? together foo. lol foo

How to remove space before each foo?


Solution

  • You can do something like:

    public String replaceSpaceBefore( String sentence, String word ) {
    
    
         return sentence.replaceAll(" " + word, word);
    
    
    }
    

    In your example, the parameter "word" would be "is" and "sentence" would be "what is your name".