fatherazrael
fatherazrael

Reputation: 5977

How to remove preceding and trailing whitespaces of Hyphen in a String, using Java or Regular expressions?

How to remove all spaces between Hyphens and preceding and trailing word in following string?

String s = "O Jesus  -   Jesus Jesus-O -     Jesus  - O -O";
s.replaceAll("  -   ", "-"); <- This only replaces first spacy-hyphen with hyphen 

We are getting other search words with Hyphen at unknown place between number of whitespaces. How regular expression can handle the same? Need global solution for same.

Output required:

"O Jesus-Jesus Jesus-O-Jesus-O-O";

Tried splitting and trimming and joining back but code looks rubbish. Need some shortcut.

Upvotes: 0

Views: 375

Answers (1)

assylias
assylias

Reputation: 328598

A regex will allow you to specify an unknown number of spaces:

s = s.replaceAll("\\s*-\\s*", "-");

where \\s* means 0 or more whitespaces.

The output will be: O Jesus-Jesus Jesus-O-Jesus-O-O

Upvotes: 3

Related Questions