zoukankan      html  css  js  c++  java
  • Java正则

    正则

    .等价于任何字符,除了
    *等价于匹配长度{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);
    	}
    

    作者:我是刘先生
    地址:https://www.cnblogs.com/cekaigongchengshi/
    文章转载请标明出处,如果,您认为阅读这篇博客让您有些收获,不妨点击一下推荐按钮,据说喜欢分享的,后来都成了大神

    欢迎扫码关注微信公众号
  • 相关阅读:
    Css实现漂亮的滚动条样式
    清除浮动的方式有哪些?比较好的是哪一种?
    Cookie、sessionStorage、localStorage的区别
    http和https的区别?
    git 拉取分支切换分支
    css 三角形
    js中??和?.的意思
    js this指向
    tsconfig.json配置
    查看本地安装的所有npm包
  • 原文地址:https://www.cnblogs.com/cekaigongchengshi/p/14084342.html
Copyright © 2011-2022 走看看