package jb.regex; import static java.lang.System.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * java1.6测试通过 * * 正则表达式语法,电话号码和email的匹配范例 * * @author * */ public class Test1 { public static void main(String[] args) { String input; String regex; Pattern p; Matcher m; /** * 正则表达式语法: * * "/d"代表数字,等价于"[0-9]" * "{3,4}"表示重复次数在3到4次之间 * * 匹配一个电话号码,区号为3或4为数字,电话为7或8为数字 */ regex = "//d{3,4}-//d{7,8}"; regex = "[0-9]{3,4}-//d{7,8}"; //与上一行的匹配模式等价 p = Pattern.compile(regex); input = "010-12345678"; m = p.matcher(input); out.println(m.matches()); //true input = "010-1234567"; m = p.matcher(input); out.println(m.matches()); //true input = "0419-12345678"; m = p.matcher(input); out.println(m.matches()); //true input = "0419-1234567"; m = p.matcher(input); out.println(m.matches()); //true out.println("---------------"); /** * * 匹配电子邮箱地址, 邮箱命名规则如下: * * 1.由字母a~z(不区分大小写)、数字0~9、点、减号或下划线组成 * 2.只能以数字或字母开头和结尾,例如:beijing.2008 * 3.用户名长度为4~18个字符 * */ regex = "[0-9a-zA-Z][0-9a-zA-Z_.-]{2,16}[0-9a-zA-Z]@[0-9a-zA-Z]+//.[0-9a-zA-Z.]+"; p = Pattern.compile(regex); input = "_abc@163.com"; m = p.matcher(input); out.println(m.matches());//false input = "abc@163.com"; m = p.matcher(input); out.println(m.matches());//false input = "abcd@163com."; m = p.matcher(input); out.println(m.matches());//false input = "ab.d@163.com"; m = p.matcher(input); out.println(m.matches());//true } } 正则表达式语法 两个范例,电话号码和EMAIL