Java使用正则表达式

1、匹配验证-验证Email是否正确

public static void main(String[] args) {
    // 要验证的字符串
    String str = "jim@jsoft.com";
    // 邮箱验证规则
    String regEx = "[a-zA-Z_]{1,}[0-9]{0,}@(([a-zA-z0-9]-*){1,}\.){1,3}[a-zA-z\-]{1,}";
    // 编译正则表达式
    Pattern pattern = Pattern.compile(regEx);
    // 忽略大小写的写法
    // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(str);
    // 字符串是否与正则表达式相匹配
    boolean rs = matcher.matches();
    System.out.println(rs);
}

2、在字符串中查询字符或者字符串

public static void main(String[] args) {
    // 要验证的字符串
    String str = "jim.jsoft.com";
    // 正则表达式规则
    String regEx = "baike.*";
    // 编译正则表达式
    Pattern pattern = Pattern.compile(regEx);
    // 忽略大小写的写法
    // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(str);
    // 查找字符串中是否有匹配正则表达式的字符/字符串
    boolean rs = matcher.find();
    System.out.println(rs);
}

3、获取匹配组的字符串

public static void main(String[] args) {
    Pattern regex = Pattern.compile("欢迎(.*),大家出来迎接新人啦!");
    Matcher regexMatcher = regex.matcher(subjectString);
    while (regexMatcher.find()) {
        for (int i = 1; i <= regexMatcher.groupCount(); i++) {
            // matched text: regexMatcher.group(i)
            // match start: regexMatcher.start(i)
            // match end: regexMatcher.end(i)
        }
    } 
}

能够自动生成代码的正则工具推荐:RegexBuddy 4

在使用matchers()判断时需要注意以下地方:

find()方法是部分匹配,是查找输入串中与模式匹配的子串,如果该匹配的串有组还可以使用group()函数。

matches()是全部匹配,是将整个输入串与模式匹配,如果要验证一个输入的数据是否为数字类型或其他类型,一般要用matches()。

原文地址:https://www.cnblogs.com/EasonJim/p/6831460.html