Java正则

正则

.等价于任何字符,除了 \n
*等价于匹配长度{0,}
+等价于匹配长度{1,}
?等价于匹配长度{0,1}
\d等价于[0-9] 匹配数字
\w等价于[A-Za-z_0-9] 匹配字母和数字
() 分组

实例:
String line = "This order was placed for QT3000! OK?";
//\\D*所有的非数字 \\d+ 所有的数字 .*匹配所有
String pattern = "(\\D*)(\\d+)(.*)";
Pattern r = Pattern.compile(pattern);
	 
	      // 现在创建 matcher 对象
	      Matcher m = r.matcher(line);
	      if (m.find( )) {
	    	  //所有表达式匹配的
              //m.group(0) 打印所有分组能匹配到集合
              //m.group(0) 打印第一组
	         System.out.println("Found value: " + m.group(0) );
	         System.out.println("Found value: " + m.group(1) );
	         System.out.println("Found value: " + m.group(2) );
	         System.out.println("Found value: " + m.group(3) ); 
	      } else {
	         System.out.println("NO MATCH");
	      }

输出结果:

Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT
Found value: 3000
Found value: ! OK?

用正则实现url的替换
private static void test() {
		//添加数据到map
		 Map<String, Object> map = new HashMap<String, Object>();
	     map.put("id", "uuid0000");
	     map.put("uid", "testuid");
	     
	      //替换逻辑 url
	     String url="http://www.baidu.com?pid=${id}&test=${uid}";
	     //规则
	     String pattern_baidu = "\\$\\{(.+?)\\}"; //非贪婪
	     Pattern r2 = Pattern.compile(pattern_baidu);
	     Matcher m2 = r2.matcher(url);
	     while(m2.find()) {
	    	     System.out.println("Found value: " + m2.group(0) );
		         System.out.println("Found value: " + m2.group(1) );
		         //replace(需要替换的字段,替换成什么内容)
		         url=url.replace(m2.group(0), map.get(m2.group(1)).toString());    
	     }
	      System.out.println(url);
	}
posted @ 2020-12-04 10:21  测开工程师成长之路  阅读(84)  评论(0)    收藏  举报