您的位置:首页 > 其它

正则表达式8种匹配实例

2014-04-20 10:51 197 查看
package zz;

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

public class ZZTest {

public static void main(String[] args) {

// 0 测试用
String s = "abc";
String regex = "abc";
testMatcher(s, regex);

// 1 匹配任意多个文字,包含特殊字符
s = "abc123_	124$%";
regex = "[\\w\\W]*";
testMatcher(s, regex);
// 2 匹配任意多个文字,不包含特殊字符
s = "abc123_	124$%";
regex = "[a-zA-Z0-9_]+";
testMatcher(s, regex);
// 3 匹配电话
s = "02221-44567890";
regex = "^([0-9]{3,4}-)?[0-9]{8}$";
testMatcher(s, regex);
// 4 匹配手机
s = "17676567788";
regex = "^1[0-9]{10}$";
testMatcher(s, regex);
// 4 匹配整数
s = "-1767622567788";
regex = "^-?[0-9]+$";
testMatcher(s, regex);
// 5 邮件地址
s = "www.@163.com";
regex = "[[a-zA-Z0-9_]]+\\.@[[a-zA-Z0-9_]]+";
testMatcher(s, regex);
// 6 小数点后一位
s = "44.2333";
regex = "-?[0-9]+\\.[0-9]{1}";
testMatcher(s, regex);
// 7 小数点后2位
s = "44.2333";
regex = "-?[0-9]+\\.[0-9]{2}";
testMatcher(s, regex);
// 7 日期格式  --本例为 1984-12-22
s = "1984-12-22";
regex = "^[1-2]?[0-9]{4}-[0-1]{1}[0-9]{1}-[1-3]{1}[0-9]{1}$";
testMatcher(s, regex);
}

public static void testMatcher(String s, String regex) {
Pattern pt = Pattern.compile(regex);
Matcher mt = pt.matcher(s);
boolean result = mt.find();
System.out.println(result + " " + (result ? mt.group() : ""));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: