正则表达式运用

正则表达式

       实际开发中,经常需要对字符串数据进行一些复杂的匹配、查找、替换等操作,通过“正则表达式”,可以方便的实现字符串的复杂操作

       正则表达式是一串特定字符,组成一个“规则字符串”,这个“字符串是描述文本规则的工具。

       正则表达式就是记录文本规则的代码

例如:

       正则表达式:“[a-z]”表示a到z的任意一个字符

       正则表达式:“[a-z]+”表示1个或多个a-z字符组成的字符串

@Test
	public void test01(){
		String regex1 = "[a-z]";
		String regex2 = "[^a-z]";
		String regex3 = "[a-z&&[^bc]]";
		String regex4 = "//d";//[0-9]
		String regex5 = "//D";//[^0-9]
		String regex6 = "//s";//[\t\n\x0B\f\r]
		String regex7 = "//S";//[^\s]
		String regex8 = "//w";//[a-zA-Z_0-9]
		String regex9 = "//W";//[^\w]
		System.out.println("a".matches(regex1));//true
		System.out.println("b".matches(regex2));//false
		System.out.println("f".matches(regex3));//true
		System.out.println("b".matches(regex3));//false
		System.out.println("1".matches(regex4));//true
		System.out.println("1".matches(regex5));//false
		System.out.println(" ".matches(regex6));//true
		System.out.println(" ".matches(regex7));//false
		System.out.println("-".matches(regex8));//true
		System.out.println("-".matches(regex9));//false
	}

 

/**
	 *测试正则表达式:“*”、“+”、“?”
	 */
	@Test
	public void test02(){
				String regex1 = "[a-z]*";
				String regex2 = "\\w+\\.jar";
				String regex3 = "\\d?[a-z]*";
				System.out.println("abcde".matches(regex1));//true
				System.out.println("".matches(regex1));//true
				System.out.println("lang.jar".matches(regex2));//true
				System.out.println(".jar".matches(regex2));//false
				System.out.println("1abc".matches(regex3));//true
				System.out.println("123abc".matches(regex3));//false
				System.out.println("abc".matches(regex3));//true
	}

 /** 测试正则表达式:"{n}"、"{n,}"、"{n,m}"*/
	 @Test
	 public void test03(){
		 String regex1 = "\\w{5}";
		 String regex2 = "\\d{5,}";
		 String regex3 = "[a-zA-Z]{5,8}";
		 System.out.println("abcef".matches(regex1));//true
		 System.out.println("abcefg".matches(regex1));//true
		 System.out.println("12345".matches(regex2));//false
		 System.out.println("123456".matches(regex2));//false
		 System.out.println("1234".matches(regex2));//false
		 System.out.println("Hello".matches(regex3));//true
		 System.out.println("HelloWorld".matches(regex3));//false
		 
	 }

检索邮政编码

规则为6位数字

第一种匹配规则

[0-9][0-9][0-9][0-9][0-9][0-9]

简化的第一种规则   \d\d\d\d\d\d

简化的第二种规则 \d{6}

分组“()”

圆括号表示分组,可以将一系列正则表达式看做一个整体,分组时可以使用“|”表示“或”的关系

例如:匹配手机号码前面的区号

边界匹配

“^”代表字符串的开始

“$”代表字符串的结束

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值