Examples of usage of Java matches Pattern and matcher classes

  • 2021-07-10 19:34:35
  • OfStack

This article illustrates the usage of Java, matches, Pattern and matcher classes. Share it for your reference, as follows:

Class Pattern

Common Rules of Regular Expressions

A: Characters
x character x. Example: 'a' for the character a
\\ Backslash character.
\ n new line (newline) character ('\ u000A')
\ r carriage return ('\ u000D')
B: Character class
[abc] a, b, or c (simple class), of which 1
[^ abc] Any character except a, b, or c (negative)
[a-zA-Z] a to z or A to Z, both letters included (range)
[0-9] Characters 0 through 9 include
C: Predefined Character Class
. Any character. Mine is. The character itself, how to express it? \.
\ d Numbers: [0-9]
\ w Word Character: [a-zA-Z_0-9]
What makes up words in regular expressions must consist of these things
D: Boundary Matcher
^ The beginning of a line
End of $line
\ b Word Boundary
Where it's not a word character.
Example: hello world? haha; xixi
E: Greedy quantifier
X? X, once or none at all
X* X, zero or more times
X + X, 1 or more times
X {n} X, exactly n times
X {n,} X, at least n times
X {n, m} X, at least n times, but not more than m times

Common features of regular expressions

A: Judgment function

Class String public boolean matches(String regex)


// Rules for defining mobile phone numbers 
 String regex = "1[38]\\d{9}";
// Call the function and judge 
boolean flag = phone.matches(regex);

fengqingyang@sina.com.cn


// Define rules for mailboxes 
String regex = "\\w+@\\w{2,6}(\\.\\w{2,3})+";
// Call the function and judge 
 boolean flag = email.matches(regex);

B: Splitting functionality

Class String public String[] split(String regex)


// Definition 1 Age search range 
String ages = "18-24";
// Define rules 
String regex = "-";
// Invoke method 
String[] strArray = ages.split(regex);
String s2 = "aa.bb.cc";
String[] str2Array = s2.split("\\.");
// The path on the hard disk, we should use \\ Substitution \
String s4 = "E:\\JavaSE\\day14\\avi";
String[] str4Array = s4.split("\\\\");

Split and sort strings


package cn.itcast_03;
import java.util.Arrays;
/*
 *  I have the following 1 String :"91 27 46 38 50"
 *  Please write code to realize that the final output is: "27 38 46 50 91"
 *
 *  Analysis: 
 *     A: Definition 1 String 
 *     B: Split the string to get 1 An array of strings 
 *     C: Converts an array of strings into int Array 
 *     D: Right int Array sorting 
 *     E: Put the sorted int Arrays are assembled into 1 String 
 *     F: Output string 
 */
public class RegexTest {
  public static void main(String[] args) {
    //  Definition 1 String 
    String s = "91 27 46 38 50";
    //  Split the string to get 1 An array of strings 
    String[] strArray = s.split(" ");
    //  Converts an array of strings into int Array 
    int[] arr = new int[strArray.length];
    for (int x = 0; x < arr.length; x++) {
      arr[x] = Integer.parseInt(strArray[x]);
    }
    //  Right int Array sorting 
    Arrays.sort(arr);
    //  Put the sorted int Arrays are assembled into 1 String 
    StringBuilder sb = new StringBuilder();
    for (int x = 0; x < arr.length; x++) {
      sb.append(arr[x]).append(" ");
    }
    // Convert to a string 
    String result = sb.toString().trim();
    // Output string 
    System.out.println("result:"+result);
  }
}

C: Replacement Features

Class String public String replaceAll(String regex,String replacement)


package cn.itcast_04;
/*
 *  Replacement function 
 *   String Class public String replaceAll(String regex,String replacement)
 *    Use the given  replacement  Replaces all substrings of this string that match the given regular expression. 
 */
public class RegexDemo {
  public static void main(String[] args) {
    //  Definition 1 String 
    String s = "helloqq12345worldkh622112345678java";
    //  Kill the numbers directly 
    String regex = "\\d+";
    String ss = "";
    String result = s.replaceAll(regex, ss);
    System.out.println(result);
  }
}

D: Get functionality

Pattern and Matcher


Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");

find() : Find if it exists
group() Get the data you just looked up


package cn.itcast_05;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
 *  Acquisition function 
 *    Pattern And Matcher Use of class 
 *
 *     Basic order of use of patterns and matchers 
 */
public class RegexDemo {
  public static void main(String[] args) {
    //  Typical invocation order of patterns and matchers 
    //  Compile regular expressions into schema objects 
    Pattern p = Pattern.compile("a*b");
    //  To get the matcher object from the schema object, what is needed at this time is the matched string 
    Matcher m = p.matcher("aaaaab");
    //  Invoke the functionality of the Matcher object 
    boolean b = m.matches();
    System.out.println(b);
    // This is a judgment function, but if you make a judgment, it will be a little troublesome to do so. We will do it directly with the string method 
    String s = "aaaaab";
    String regex = "a*b";
    boolean bb = s.matches(regex);
    System.out.println(bb);
  }
}


package cn.itcast_05;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
 *  Get functionality: 
 *  Gets the following string from 3 Words consisting of three characters 
 * da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?
 */
public class RegexDemo2 {
  public static void main(String[] args) {
    //  Definition string 
    String s = "da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?";
    //  Rules 
    String regex = "\\b\\w{3}\\b";
    //  Compile rules into schema objects 
    Pattern p = Pattern.compile(regex);
    //  Obtaining Matcher Objects from Pattern Objects 
    Matcher m = p.matcher(s);
    while (m.find()) {
      System.out.println(m.group());
    }
    //  Note: 1 Be sure to go first find() , and then you can group()
    // IllegalStateException: No match found
    // String ss = m.group();
    // System.out.println(ss);
  }
}

PS: Here are two very convenient regular expression tools for your reference:

JavaScript Regular Expression Online Test Tool:
http://tools.ofstack.com/regex/javascript

Regular expression online generation tool:
http://tools.ofstack.com/regex/create_reg

More readers interested in java algorithm can check the topics of this site: "Java Regular Expression Skills Encyclopedia", "Java Character and String Operation Skills Summary", "Java Data Structure and Algorithm Tutorial", "Java Operation DOM Node Skills Summary" and "Java File and Directory Operation Skills Summary"

I hope this paper is helpful to everyone's java programming.


Related articles: