Java - Regular Expressions Regular Expressions

What Is a Regular Expression?

A regular expression describes a pattern in a sequence of characters.

String API

String class has two methods to do the match replacement with Regular Expressions

String replaceAll(String regex, String replacementString):
String replaceFirst(String regex, String replacementString):

Some examples of using the replaceAll() method are as follows:

Demo

public class Main {
  public static void main(String[] args) {
    String regex = ".@.";

    String s = "asdf@book2s.com".replaceAll(regex, "***");
    System.out.println(s);//w ww  .j a v  a 2s .  co  m
    s = "A@B".replaceAll(regex, "***");
    System.out.println(s);
    s = "A@abc@G".replaceAll(regex, "***");
    System.out.println(s);
    s = "abc%def".replaceAll(regex, "***");
    System.out.println(s);

  }
}

Result

replaceFirst() method replaces the first occurrence of the match.

Demo

public class Main {
  public static void main(String[] args) {
    String regex = ".@.";

    String s = "asdf@book2s.com".replaceFirst(regex, "***");
    System.out.println(s);/*from w w w . j a v  a  2s  .co m*/
    s = "A@B".replaceFirst(regex, "***");
    System.out.println(s);
    s = "A@abc@G".replaceFirst(regex, "***");
    System.out.println(s);
    s = "abc%def".replaceFirst(regex, "***");
    System.out.println(s);

  }
}

Result

Exercise