JAVA中正则表达式的使用

如果出现连续相同的要分割的字符,那么会出现空字符串

1.split方法 2.pattern类编译正则3.matches类匹配正则

 public class RegexTest { 
     public static void main(String[] args) { 
         String name = "01_My-File.pdf" ; 
         match(name); 
         match( "09_03_12File.docx" ); 
         match( "09_03_12File.q123" ); 
     } 
     public static void match(String input){ 
         System.out.println( "********* Analysing " + input+ " *********" ); 
         String regex = "([0-9]+)([_])(.*)([\\.])([A-Za-z]+)" ; 
         Pattern pattern = Pattern.compile(regex); 
         Matcher matcher = pattern.matcher(input); 
         if (!matcher.matches()){ 
             System.out.println( "Input not matches regex" ); 
             return ; 
         } 
         System.out.println( "Matches: " + matcher.matches()); 
         String number = matcher.group(1); 
         System.out.println( "Index: " + number); 
         String fileName = matcher.group(3); 
         System.out.println( "FileName: " + fileName); 
         String extension = matcher.group(5); 
         System.out.println( "Extension: " + extension); 
     }  } 

请添加图片描述

注:matches是全局匹配,也就是需要模式与输入序列完全匹配才返回true,looking At方法也是从头开始, 不同于matches方法,它不要求整个区域匹配

但是 Matcher类中的find方法是搜索匹配,只需要输入序列中有满足模式的即可,而且索引还会随之变化(start,end方法(end方法返回的是上一次匹配结束时查到的索引)进行返回上一次匹配的索引)

请添加图片描述
请添加图片描述

更多推荐