开发者

Replace sequence of dots with one underscore

I have a string holding any number of dots, sometimes also a sequence of dots.

I want to replace every . (dot) by 开发者_开发知识库_ (underscore) but when there is a sequence of dots, this should also result only in a single underscore.

Any ideas?

I`m using java.


You can use the replaceall method as:

str = str.replaceAll("\\.+","_");

See it on Ideone

Explanation of the regex \\.+

. is a regex metacharacter to match anything (except newline). Since we want to match a literal . we escape it with \. Since both Java Strings and regex engine use \ as escape character we need to use \\, + is the quantifier for one or more.

Alternatively we can use:

str = str.replaceAll("[.]+","_");

Since a . inside a character class is treated literally there is not need to escape it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜