Raghavan Raghavan - 5 months ago 10
Java Question

Replace white spaces only in part of the string

I have a String like

"This is apple tree"


I want to remove the white spaces available until the word apple.After the change it will be like

"Thisisapple tree"


I need to achieve this in single replace command combined with regular expressions.

Answer

For now it looks like you may be looking for

String s = "This is apple tree";
System.out.println(s.replaceAll("\\G(\\S+)\\s(?!tree)", "$1"));

Output: Thisisapple tree.


WARNING: This solution assumes that

  • sentence doesn't start with space,
  • words can be separated with only one space.