首页 > 解决方案 > Trying to replace a point and spaces inside a sentence using regex

问题描述

I am trying te replace points and spaces inside a sentence with a dash using regex. I have now for example this:

String test = "Hello. everyone and ha.ve a nice .day";
test = test.replaceAll(" ", "-");

And want to result to be like this:

Hello-everyone-and-ha-ve-a-nice-day

I would appreciate it if someone is able to help me with a solution to my problem.

标签: regex

解决方案


您可以使用

String test = "Hello. everyone and ha.ve a nice .day";
test = test.replaceAll("[. ]+", "-");

或者

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

请参阅正则表达式演示

\s模式匹配任何空格,而不仅仅是常规空格字符。

[.\s]是一个匹配点或空白字符的字符类+是一个“重复”模式一次或多次的量词。


推荐阅读