简体   繁体   中英

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.

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-OO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM