首页 > 代码库 > java之正则表达式

java之正则表达式

不使用正则表达式:

import java.util.Scanner;

public class RagexDemo01 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next();
        boolean flag = true;
        char[] c = str.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] < ‘0‘ || c[i] > ‘9‘) {
                flag = false;
                System.out.println("fffffffff");
                break;
            }
        }
        if (flag) {
            System.out.println("All is number!");
        } else {
            System.out.println("Not all is number!");
        }
    }
}

使用正则表达式:

import java.util.Scanner;
import java.util.regex.Pattern;

public class RegexDemo02 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String string = scanner.next();
        if (Pattern.compile("[0-9]+").matcher(string).matches()) {
            System.out.println("ALL IS NUM!");
        } else {
            System.out.println("NOT ALL IS NUM!");
        }
    }
}

如果要在程序中应用正则表达式则必须依靠Pattern类与Matcher类,这两个类都在java.util.regex包中定义。Pattern类的主要作用是进行正则规范的编写,而Matcher类主要是执行规范,验证一个字符串是否符合其规范。

 

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexDemo03 {
    public static void main(String[] args) {
        String str = "19W3-12-51";
        String pat = "\\d{4}-\\d{2}-\\d{2}";
        Pattern p = Pattern.compile(pat);
        Matcher m = p.matcher(str);
        if (m.matches()) {
            System.out.println("OKKKKKK!");
        } else {
            System.out.println("NOOOOOO!");
        }
    }
}

 

按数字拆分字符串:

public class RegexDemo04 {
    public static void main(String[] args) {
        String str = "A1BFOEIWOEF02223IOFEJW09323";
        String pat = \\d;  // \d 代表数字
        Pattern p = Pattern.compile(pat);
        String s[] = p.split(str);
        for (int x = 0; x < s.length; x++) {
            System.out.println(s[x] + "\t");
        }
    }
}

替换所有数字为#:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexDemo05 {
    public static void main(String[] args) {
        String str = "A1B32GEJO31BFEO231NFE";
        String pat = "\\d+";
        Pattern p = Pattern.compile(pat);
        Matcher m = p.matcher(str);
        String newString = m.replaceAll("#");
        System.out.println(newString);
    }
}

直接使用string类的支持正则表达式的方法:

public class RegexDemo06 {
    public static void main(String[] args) {
        String str1 = "A3OFE21FAFEO23FAF321".replaceAll("\\d", "#");
        boolean temp = "1932-32-12".matches("\\d{4}-\\d{2}-\\d{2}");
        String s[] = "A1L309LFE233202FAG21LF".split("\\d+");
        System.out.println(str1);
        System.out.println(temp);
        for (int x = 0; x < s.length; x++) {
            System.out.println(s[x] + "\t");
        }
    }
}