简体   繁体   中英

How can I avoid repeating the replacement character when replacing substrings

I have the following string in a database

**final test project - test decorations**

and I want to replace spaces with dashes ( the - character ). This is what I have so far:

tit1 = rs.getString("title");
tit1 = tit1.replaceAll("\\s{1}", "-");

The outputs looks like this

**final-test-project---test-decorations**
  **shadow-of-the-test----test**

but i want output like this

**final-test-project-test-decorations**
   **shadow-of-the-test-test**

How can I make the replacement ignore the single dash surrounded with whitespaces?

You may use the following line

tit1 = tit1.replaceAll("[\\s-]+", "-");

instead of your call to replaceAll . It takes all consecutive spaces together with dashes and replaces them by a single dash.

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