获取功能- 模式Pattren 和匹配器 Matcher

前端之家收集整理的这篇文章主要介绍了获取功能- 模式Pattren 和匹配器 Matcher前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


获取 模式Pattren 和匹配器 Matcher

1.获取模式Pattern
Pattern pattern=Pattern.compile("a*b*");
2.获取匹配器Matcher

Matcher matcher=pattern.matcher("aaa");


模式Pattren 和匹配器 Matcher的获取

  1. public static void main(String[] args){
  2. //获取模式Pattern
  3. Pattern pattern=Pattern.compile("a*b*");
  4. //获取匹配器Matcher
  5. Matcher matcher=pattern.matcher("aaa");
  6.  
  7.  
  8. boolean b=matcher.matches();
  9. System.out.print(b);


获取字符串中长度为3的单词

  1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;
  3.  
  4. /**
  5. * Created by hanshan on 2016/12/29.
  6. */
  7. public class MatcherPattern2 {
  8. public static void main(String[] args){
  9. String s="wo ai wo de jia,tom loves his jia too";
  10. Pattern pattern=Pattern.compile("\\b\\w{3}\\b");
  11. Matcher matcher=pattern.matcher(s);
  12. /* boolean b=matcher.find();
  13. System.out.print(b);
  14. String result=matcher.group();
  15. System.out.print(result);*/
  16. while(matcher.find()){
  17. String ans=matcher.group();
  18. System.out.print(ans+" ");
  19. }
  20. // 注意:一定要先find(),然后才能group()
  21. // IllegalStateException: No match found
  22. // String ss = m.group();
  23. // System.out.println(ss);
  24. }
  25. }

猜你在找的正则表达式相关文章