javaregexreplace

Java: replace character inside a matching regex


I have a string. Let's say:
String s = "This is my P.C.. My P.C. is the best.O.M.G!! Check this...";

I want to replace all the P.C. to PC words and O.M.G to OMG. In general, I want to replace all the dots that are between single letters OR single letter and a space or dot. I think the matching regex for that is:

[^A-Za-z][A-Za-z]\\.[A-Za-z\\s\\.][^A-Za-z]

How can I replace only the dot from that and not everything that matches?

EDIT:

Expected output:

"This is my PC. My PC is the best.OMG!! Check this..."

EDIT2:

The basic task is to remove dots from abbreviations and acronyms that could be written with or without dots. So a good regex is also valuable


Solution

  • You may consider using Positive Lookahead to assert what follows is either a letter, dot . or space.

    String s = "This is my P.C.. My P.C. is the best.O.M.G!! Check this...";
    String r = s.replaceAll("([A-Z])\\.(?=[ A-Z.])", "$1");
    System.out.println(r); //=> "This is my PC. My PC is the best.OMG!! Check this..."