zoukankan      html  css  js  c++  java
  • Java SE之正则表达式Demo

    @Test
    	public void regex() {//匹配教务系统课程
    //		String content = "公共机座 (1-10)".replaceAll(" ","");
    		String content = "6A-411公共机房50座 (1-10)".replaceAll(" ","");//标准格式 //6A-411;1-10;50
    //		String pattern = "^(\d+)([a-zA-Z])-(\d+)([u2E80-u9FFF]+)(\d+)([\u2E80-\u9FFF]+)......";//原始完全匹配
    		String pattern = "^(?<arg1>\d+\S+(-)(\d+))([u2E80-u9FFF]+)(?<arg2>\d+)([\u2E80-\u9FFF]+).(?<arg3>\S+).";
    		String [] items = content.split(pattern);
    		StringBuilder temp = new StringBuilder();
    		for(String item : items) { 
    			temp.append(item);
    		}
    		System.out.println(temp);
    
    		Matcher matcher = Pattern.compile(pattern).matcher(content);
            if(matcher.matches()){
            	System.out.println("arg1:" + matcher.group("arg1"));
            	System.out.println("arg2:" + matcher.group("arg2"));
            	System.out.println("arg3:" + matcher.group("arg3"));
            }
            System.out.println(content);
    	}    
    

    输出:

    arg1:6A-411
    arg2:50
    arg3:1-10
    6A-411公共机房50座(1-10)
    

    正则的用途:匹配、搜索、替换、验证

    1.要点1:[]用于仅能匹配一个字符

    2.要点2:()用于固定某种字符串格式

    3.要点3:中文utf8范围:[u2E80-u9FFF]

    4.要点4:在正则表达式中设置参数断点格式:(?<argmentName>(regex1)(regex2)(regexN))

  • 相关阅读:
    (数论选拔)联盟阵容
    ai变成bi(递增)最小次数
    状压dp
    dp被3整除的子序列
    离散化+莫队
    dp+哈希
    set的应用
    NOIP 2016 明明的随机数
    洛谷背景更改
    zzulioj 1734 堆
  • 原文地址:https://www.cnblogs.com/johnnyzen/p/7854066.html
Copyright © 2011-2022 走看看