A regular expression describes a pattern in a sequence of characters.
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:
public class Main { public static void main(String[] args) { String regex = ".@."; String s = "asdf@book2s.com".replaceAll(regex, "***"); System.out.println(s);/*from w w w .ja va 2 s. c om*/ 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); } }
replaceFirst() method replaces the first occurrence of the match.
public class Main { public static void main(String[] args) { String regex = ".@."; String s = "asdf@book2s.com".replaceFirst(regex, "***"); System.out.println(s);/*from w ww .java2 s .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); } }