Replacing characters in a string, Java

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

+5
source share
4 answers

Replace a point only when it is surrounded by two characters

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

Or as @Thilo commented only if it is surrounded by two inaccuracies

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

And to replace a single point with two points, even if the point is at the beginning / end of the line, use a negative lookahead and lookbehind: (Example Line: .abc.def..ghi. Becomes ..abc..def..ghi.. )

 String foo = s.replaceAll("(?<!\\.)\\.(?!\\.)", ".."); 
+6
source

If you don't know how to do this using regex, use a StringTokenizer to split the String and concatenate again with ..

code:

 public static void main(String[] args) { String s = "abc.def..ghi"; StringTokenizer s2 = new StringTokenizer(s, "."); StringBuilder sb = new StringBuilder(); while(s2.hasMoreTokens()) { sb.append(s2.nextToken().toString()); sb.append(".."); } sb.replace(sb.length()-2, sb.length(), ""); // Just delete an extra .. at the end System.out.println(sb.toString()); } 

I know that the code is large compared to one regular expression of a string, but I sent it in case you have problems with the regular expression. If you think this is slower than the accepted answer, I made a start and end time using System.currentTimeMillis() and I got my speed faster. I do not know if there are exceptions for this test.

Anyway, I hope this helps.

+3
source

Use appearance:

 str = str.replaceAll("(?<!\\.)\\.(?!\\.)", "..")( 

The regular expression reads as "a point not preceded by a point, not a point." This will handle boundary cases when the point is at the beginning / end and / or is surrounded by literally any other character.

Since the appearance does not consume input, you do not need to give up backlinks in terms of replacement.

+2
source
 s.replace("...",".."); s.replace("....",".."); 

Depends on input options.

-6
source

Source: https://habr.com/ru/post/1259996/


All Articles