Raghavan Raghavan - 1 year ago 59
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 Source

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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download