Http://www.cnblogs.com/nerxious/archive/2013/01/03/2842910.html
Regular expressions are quite efficient at handling strings.
About the use of regular expressions, more of their own experience, interested can refer to related books
Here are the main things to write about the regular operation method in Java
Example 1: Matching
Import Java.util.scanner;class Demo {public static void Main (string[] args) { Scanner sc = new Scanner (system.in) ; Get input System.out.print ("Please enter:"); String str = sc.nextline (); Check (str); } private static void Check (String str) { //Match first bit is 1-9, second bit and later 0-9 (number in 4-10) String regex = "[1-9][0-9]{4,10}"; /*//Match single character is case-A-Z String regex = "[A-za-z]"; Match numbers, note the escape character String regex = "\\d"; Matches a non-numeric String regex = "\\d"; */ if (str.matches (regex)) { System.out.println ("Match succeeded"), } else { System.out.println ("Match failed"); } }}
The matches () method in the string class here is used to match
Example 2: Cutting
Import Java.util.scanner;class Demo {public static void Main (string[] args) { Scanner sc = new Scanner (system.in) ; System.out.print ("Please Enter:"); String str = sc.nextline (); Split (str); } private static void Split (String str) { //matches one or more spaces string regex = "+"; string[] arr = str.split (regex); for (String S:arr) { System.out.println (s);}} }
Here the split () method in the string class is used to cut by regular expression, returning a string array
Example 3: Replace
Import Java.util.scanner;class Demo {public static void Main (string[] args) { Scanner sc = new Scanner (system.in) ; System.out.print ("Please Enter:"); String str = sc.nextline (); Replace (str); } private static void replace (String str) { //Match overlapping string regex = "(.) \\1+ "; String s = str.replaceall (Regex, "*"); System.out.println (s); }}
Note that the ReplaceAll has two parameters, one is a regular, the other is a replacement character
Summary of regular operations in Java