正则表达式

来源:互联网 发布:网络点播系统 编辑:程序博客网 时间:2024/06/09 18:39

最近需要用到正则表达式来做一些匹配的内容,下面是一些具体的语法和使用例子。

1)、语法

使用 [  ] 表示选择,使用()进行分组.

2)、常用正则表达式
规则正则表达式语法  一个或多个汉字^[\u0391-\uFFE5]+$ 邮政编码^[1-9]\d{5}$QQ号码^[1-9]\d{4,10}$ 邮箱^[a-zA-Z_]{1,}[0-9]{0,}@(([a-zA-z0-9]-*){1,}\.){1,3}[a-zA-z\-]{1,}$ 用户名(字母开头 + 数字/字母/下划线)^[A-Za-z][A-Za-z1-9_-]+$手机号码^1[3|4|5|8][0-9]\d{8}$ URL^((http|https)://)?([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$ 18位身份证号^(\d{6})(18|19|20)?(\d{2})([01]\d)([0123]\d)(\d{3})(\d|X|x)?$3)、实例

①验证邮政编码是否正确

/**
 * Created with IntelliJ IDEA.
 * User: shuaiy
 * Date: 16-9-19
 * Time: 下午8:52
 * To change this template use File | Settings | File Templates.
 */
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Matches {
    public static void main(String []args){
        boolean result;
        String line = "610100";
        String pattern = "^[1-9]\\d{5}$";
        Pattern r =Pattern.compile(pattern);//创建pattern对象
        Matcher m = r.matcher(line);

        result = m.find();
        System.out.println(result);
    }
}

②验证邮箱格式是否合法

import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: shuaiy
 * Date: 16-9-24
 * Time: 下午3:00
 * To change this template use File | Settings | File Templates.
 */
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class MatcherEmain {
    public static void main(String args[]){
        String email = "c120102@163.com";
        boolean result;
        String pattern = "^[a-zA-Z_]{1,}[0-9]{0,}@(([a-zA-z0-9]-*){1,}\\.){1,3}[a-zA-z\\-]{1,}$";
        Pattern r= Pattern.compile(pattern);
        Matcher m = r.matcher(email);

        result =m.matches();
        System.out.println(result);
    }
}


0 0
原创粉丝点击