Sergiu
Sergiu

Reputation: 2626

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.

Upvotes: 2

Views: 4863

Answers (1)

codaddict
codaddict

Reputation: 455102

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.

Upvotes: 10

Related Questions