加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式8种匹配实例

发布时间:2020-12-14 01:48:04 所属栏目:百科 来源:网络整理
导读: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 匹配任意多个文字,包含特殊字符
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 = "[wW]*";
		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() : ""));
	}
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读