Java - 正则表达式

package test.regexp;

import java.util.regex.Pattern;

/*
 * 1. . 匹配任何单个字符
 * t.b   --->   tab,t b,...
 * 
 * 2. [] 单个字符
 * t[aeo]b  --->  tab, teb, tob
 * 
 * 3. () 分组
 * t(a|e)b  --->  tab, teb
 * 
 * 4. |  或者
 * 
 * 5. $  结尾匹配
 * 6. ^  开始匹配    如果出现在 () [] 中表示否的意思
 * 
 * ---------------  范围  ---------------
 * 7. *  0个以上
 * 8. +  1个以上
 * 9. ?  0次或者1次
 * 10. {n} n次
 * 11. {n,} 至少n次
 * 12. {n, m} 至少n次,至多m次
 * 13. -  返回    0-9 数字    a-z  小写字母
 * 
 * ---------------  转义  ---------------
 * 14. \s  空白符号      用法一般为  "\\s"
 * 15. \S  非空白符
 * 16. \d  数字
 * 17. \D  非数字
 * 18. \w  字母    等同于[a-zA-Z_0-9]
 * 19. \W  非字母
 * 
 * 反斜线字符 ('\') 用于引用转义构造,如上表所定义的,同时还用于引用其他将被解释为非转义构造的字符。
 * 因此,表达式 \\ 与单个反斜线匹配,而 \{ 与左括号匹配。
 * 在不表示转义构造的任何字母字符前使用反斜线都是错误的;它们是为将来扩展正则表达式语言保留的。
 * 可以在 非字母字符 前使用反斜线,不管该字符是否非转义构造的一部分。
 * 根据 Java Language Specification 的要求,Java 源代码的字符串中的反斜线被解释为 Unicode 转义或其他字符转义。
 * 因此必须在字符串字面值中使用两个反斜线,表示正则表达式受到保护,不被 Java 字节码编译器解释。
 * 例如,当解释为正则表达式时,字符串字面值 "\b" 与单个退格字符匹配,而 "\\b" 与单词边界匹配。
 * 字符串字面值 "\(hello\)" 是非法的,将导致编译时错误;要与字符串 (hello) 匹配,必须使用字符串字面值 "\\(hello\\)"。
 * 
 */

public class RegexpTest {

	public static void main(String[] args) {
		
//		String regStr1 = "tob";
//		System.out.println(regStr1.matches("t.b"));  // true
//		
//		String regStr2 = "toob";
//		System.out.println(regStr2.matches("t(.)(.)b"));  // true   括号分组
//		System.out.println(regStr2.matches("t[o|oo]b"));  // false  中括号只能匹配单个字符
//		System.out.println(regStr2.matches("t(o|oo)b"));  // true
		
//		String regStr3 = "hello world";
//		System.out.println(regStr3.matches("world$"));  // false
//		System.out.println(regStr3.matches("^hello"));  // false
//		System.out.println(regStr3.matches("hello world")); // true
//		System.out.println(regStr3.matches("^h(.*)d$"));  // true  以h开始d结束,中间有任意个字符
		
		String regStr4 = "/user/10404";
		String regPath = "/user/{id}";
//		System.out.println(regPath.matches(".+{\\w+}.*"));  // 语法错误
//		System.out.println(regPath.matches(".+\\{\\w+\\}.*")); // true  // \\{ 匹配{  \\w 匹配字符
//		regPath = regPath.replaceAll("\\{\\w+\\}", "(\\w+)");
//		System.out.println(regPath); // /user/(w+)
		
		regPath = regPath.replaceAll("\\{\\w+\\}", "(\\\\w+)");
		System.out.println(regPath);  // /user/(\w+)  // 形成正则表达式字符串
		System.out.println(regStr4.matches(regPath)); // true
		
		Pattern regPattern = Pattern.compile(regPath);
		Matcher matcher = regPattern.matcher(regStr4);
		System.out.println(matcher.matches());  // true
	}
}


转载于:https://my.oschina.net/kuangcaibao/blog/425724

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值