Pattern.matches 方法适用于设置尚可接受而且只需进行一次测试的状况 (整个序列全匹配时才返回true)。java
boolean b = Pattern.matches("[T|t]rue", "true");System.out.println(b);true[Yy]es[Tt]rue时返回fale,因为不是整个序列匹配输入字符串"true"
boolean a = "true".matches("[a-z]{4}");System.out.println(a);true
Pattern pattern = Pattern.compile("[A-Z][a-z]*", Pattern.CASE_INSENSITIVE | Pattern.UNIX_LINES);
split方法使用,分隔字符串正则表达式
Pattern pattern = Pattern.compile(",");String string = "sa,ad,fd,c,we,d,a";String[] strings = pattern.split(string);for (String s : strings) { System.out.println(s);}
Pattern对象是线程安全的,Matcher类对象是非线程安全的,由于它们在方法调用之间保有内状态。安全
matcher对象能够重复使用,因为matcher非线程安全,因此须要在每次matcher时调用复位器rest()app
Pattern pattern = Pattern.compile("正则表达式");Matcher matcher = pattern.matcher("");String line;BufferedReader reader = new BufferedReader(new FileReader("文件路径"));while ((line = reader.readLine()) != null) { //复位器,因为matcher非线程安全 matcher.reset(line); if (matcher.find()) { System.out.println("file == " + line); } reader.close();}
Matcher中的matchers()与Pattern.matcher()用法相同,整个字符匹配才true;测试
lookingAt(),匹配开始spa
lookingAt( )方法与 matches( )类似,可是它不要求整个序列的模式匹配。若是正则表达式 模式匹配字符序列的beginning(开头),则lookingAt( )返回true。lookingAt( )方法每每从序列 的头部开始 。该方法的名字暗示了匹配程序正在 查看 目标是否以模式开头。若是返回 为true,那么能够调用start( )、end( )和group( )方法匹配的子序列的范围。线程
find(),循环匹配rest
find( )方法运行的是与 lookingAt( )相同类型的匹配操做,可是它会记 前一个匹配的位置 并在以后从新开始 。从而容许了相继调用 find( )对输入进行逐句比对,寻找 入的匹配。 复位后第一次调用该方法,则 将从输入序列的首个字符开始。在随后调用中,它将从前一 个匹配的子序列后面的第一个字符从新开始 。如各个调用来讲,若是找到了模式将返回true;反之将返回 false。一般你会使用 find( )循环访问一些文原本查找其中全部匹配的模式。 code
//find循环匹配,返回开始结束位置,提取子序列 if (matcher.find( )) { subseq = input.subSequence (matcher.start(), matcher.end( )); }
start(),end()须要在matches(),lookingAt(),find()调用后才有意义,匹配空字符串start=end对象
group(),表达示捕获组,从左至右
String match0 =input.subSequence (matcher.start(), matcher.end()).toString(); String match2 = input.subSequence (matcher.start (2),matcher.end (2)).toString() //上述代码与下列代码等效: //group()无参数,返回组0,即所有匹配项 String match0 = matcher.group(); String match2 = matcher.group(2);
replaceFirst(),replaceAll()替换字符
pattern.complie("[Bb]yte");
String replace ="$lite";
matcher.replaceFirst/replaceAll(replace);
java中的转义字符须要增长两个反斜杠,\表示为\\,若是再使用正则来replace则须要再增长\\,最终结过两次转换事后\\\\表明一个 \。
appendReplacement() appendTail()
appendReplacement() find后,复制查找的内容到新的StringBuffer,而后替换新的StringBuffer中的字符(不会理会原字符串中的未查找到的部份如何处理,只处理查找到的部份);
appendTail() 恰好相反,复制查找的内容到新的StringBuffer,既处理查找部分字符,一样处理原字符串的余下部。份。
Pattern pattern = Pattern.compile("([Tt])hanks"); Matcher matcher = pattern.matcher("Thanks, thanks very much"); StringBuffer sb = new StringBuffer(); while (matcher.find()) { if (matcher.group(1).equals("T")) { matcher.appendReplacement(sb, "Thank you"); } else { matcher.appendReplacement(sb, "thank you"); } } matcher.appendTail(sb); System.out.println(sb.toString()); }
String类已添加的公用正则表达式
matches,split,relaceFirst,replaceAll
Java正则是占有型量词 (possessive quantifier),它们比常规的贪婪量 (greedy quantifier)还要贪婪。占有型量词会尽量地多匹配目标。