Matcher类

2018-04-12  本文已影响0人  李望洲_3c80

Matcher类

常用方法及介绍

boolean matches() 最常用方法:尝试对整个目标字符展开匹配检测,也就是只有整个目标字符串完全匹配时才返回真值.

Pattern pattern = Pattern.compile("\\?{2}");Matcher matcher = pattern.matcher("??");boolean matches = matcher.matches();//trueSystem.out.println(matches);matcher=pattern.matcher("?");matches = matcher.matches();//falseSystem.out.println(matches);

boolean lookingAt() 对前面的字符串进行匹配,只有匹配到的字符串在最前面才会返回true

Pattern p = Pattern.compile("\\d+");Matcher m = p.matcher("22bb23");boolean match = m.lookingAt();//trueSystem.out.println(match);m = p.matcher("bb2233");match= m.lookingAt();System.out.println(match);//false

boolean find() 对字符串进行匹配,匹配到的字符串可以在任何位置

Pattern p = Pattern.compile("\\d+");Matcher m = p.matcher("22bb23");m.find();// 返回trueMatcher m2 = p.matcher("aa2223");m2.find();// 返回trueMatcher m3 = p.matcher("aa2223bb");m3.find();// 返回trueMatcher m4 = p.matcher("aabb");m4.find();// 返回false

int start() 返回当前匹配到的字符串在原目标字符串中的位置

int end() 返回当前匹配的字符串的最后一个字符在原目标字符串中的索引位置.

String group() 返回匹配到的子字符串 

Pattern.start(),Pattern.end(),Pattern.group()代码示例

Pattern p = Pattern.compile("\\d+");Matcher m = p.matcher("aa22bb23");m.find();int start = m.start();//2String group = m.group();//22int end = m.end();//4System.out.println(start);System.out.println(group);System.out.println(end);

上一篇 下一篇

猜你喜欢

热点阅读