Mamba
Mamba

Reputation: 1203

How to match special characters and replace the corresponding string?

Learning regular expressions, Im trying to replace some words which have @ and . inside like an email adress in my example. I have tried several combinations but none has worked out.

public class extraction {

        public static void main(String args[]){

            String outText="";
            String inText="Hello my email as [email protected] and not me@goolgle; but you can also use  [email protected]";
            outText = inText.replaceAll("/[@/\\.]", "NOTAVAILABLE");
            System.out.println(outText);

            // Expected: Hello my email as NOTAVAILABLE and not me@goolgle; but you can also use  NOTAVAILABLE

        }

    }

Appreciate any suggestions!

Upvotes: 2

Views: 61

Answers (1)

anubhava
anubhava

Reputation: 785611

You can use this regex for search:

[^\s@]+@[^\s.]+\.\S+

and replace by "NOTAVAILABLE" string.

RegEx Demo

Code:

str = str.replaceAll("[^\\s@]+@[^\\s.]+\\.\\S+", "NOTAVAILABLE");

Explanation:

  • [^\s@]+: Match 1+ characters that are not whitespace and not a @
  • @: Match @
  • [^\s.]+: Match 1+ characters that are not whitespace and not a dot
  • \.: Match a literal dot
  • \S+: Match 1+ non-whitespace characters

Code Demo (courtesy @ctwheels)

Upvotes: 2

Related Questions