Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing characters in a string, Java

Tags:

java

string

regex

I have a string like s = "abc.def..ghi". I would like to replace the single'.' with two '.'s. However, s.replace(".", "..") yields "abc..def....ghi". How can I get the correct behaviour? The output I'm looking for is s = "abc..def..ghi".

like image 864
Adam Avatar asked Nov 19 '16 02:11

Adam


1 Answers

Replace the dot only when it's surrounded by two characters

String foo = s.replaceAll("(\\w)\\.(\\w)", "$1..$2");

Or as @Thilo commented, only if it's surrounded by two non dots

String foo = s.replaceAll("([^.])\\.([^.])", "$1..$2");

And to replace the single dot with two dots even if the dot is at the beginning/end of the string, use a negative lookahead and lookbehind: (Example String: .abc.def..ghi. will become ..abc..def..ghi..)

String foo = s.replaceAll("(?<!\\.)\\.(?!\\.)", "..");
like image 93
baao Avatar answered Sep 22 '22 05:09

baao