Method summary based on regular operations in Java

  • 2020-04-01 01:47:00
  • OfStack

Regular expressions are quite efficient at handling strings

The use of regular expressions is more about your own experience, and you can refer to the relevant books if you are interested

Here I'll focus on the regular action methods in Java

Example 1: match

import java.util.Scanner; 
class Demo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //Access to the input
        System.out.print("Please Enter:");
        String str = sc.nextLine();
        check(str);
    }
    private static void check(String str) {
        //The first is 1-9, the second is 0-9 (number between 4-10)
        String regex = "[1-9][0-9]{4,10}";

        /*
        //Matching individual characters is case a-z
        String regex = "[a-zA-Z]";
        //Match Numbers, and watch for escape characters
        String regex = "\d";
        //Matching nonnumber
        String regex = "\D";
        */

        if(str.matches(regex)) {
            System.out.println(" The match is successful ");
        } else {
            System.out.println(" Matching failure ");
        }
    }
}

Here the matches() method in the String class is used for matching

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013050318361177.png ">

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

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013050318361178.png ">

Example 3: substitution


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 the reiterative
        String regex = "(.)\1+";
        String s = str.replaceAll(regex, "*");
        System.out.println(s);
    }
}

Notice that replaceAll takes two parameters, a regular and an alternate character

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013050318361179.png ">


Related articles: