Peiboludo
Peiboludo

Reputation: 71

in Java how can I replace "space and dot" to only "dot"?

i have for example this:

"hello . world . thanks ."

and i want to get this:

"hello. world. thanks."

I have try

text = text.replaceAll(" .",".");
text = text.replaceAll(" \\.",".");
text = text.replaceAll(" \\.","\\.");

but it doesn´t work. Any solution??

Thanks for all

Upvotes: 3

Views: 9310

Answers (3)

Anirudha
Anirudha

Reputation: 32797

Your second method should have worked.

I guess you may have 1 to many space or tabs before ..In that case you need to use + quantifier to match 1 to many space if you have them

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

Since . has a special meaning in regex you need to escape it using \\. or [.] which would treat . literally

\s is similar to [ \t\r\n]

Upvotes: 5

Vanquish46
Vanquish46

Reputation: 534

replaceAll uses regex for the first arguement. If you want something really simple (aka for the example given, assuming your actual problem isn't a lot more complex) you can just use replace.

text = text.replace(" .", ".");

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replace(java.lang.CharSequence, java.lang.CharSequence)

Upvotes: 7

Jon Skeet
Jon Skeet

Reputation: 1500765

I would suggest you don't use String.replaceAll to start with. You don't need regular expressions here, so why make it harder for yourself? Use String.replace instead.

text = text.replace(" .", ".");

Upvotes: 3

Related Questions