简体   繁体   English

替换子字符串时如何避免重复替换字符

[英]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 . 而不是您调用replaceAll It takes all consecutive spaces together with dashes and replaces them by a single dash. 它会将所有连续的空格与破折号一起使用,并用一个破折号代替它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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