首页 > 编程语言 > 详细

java正则表达式

时间:2018-04-21 22:07:45      阅读:201      评论:0      收藏:0      [点我收藏+]

1, [abc] a, b 或 c

       [^abc] 任何字符,除了a,b 或 c

  [a-zA-Z] a 到 z 或 A 到 Z,两头字符都包括在内

  [a-d[m-p]] a 到 d 或 m 到 p :[a-dm-p](并集)

  [a-z&&[def]] d,e 或 f(交集)

2, * 任何字符

  \d 数字: [0-9]

  \D 非数字:[^0-9]

  \s 空白字符:[\t\n\x0B\f\r]

  \S 非空白字符:[^\s]

  \w 单词字符:[a-zA-Z_0-9]

  \W 非单词字符:[^\w]

3, Greedy 数量词

  X?  一次或一次也没有

  X*  零次或多次

  X+  一次或多次

  X{n}  恰好n次

  X{n,}  至少n次

  X{n,m}  至少n次,但是不超过m次字符串

4, 替换功能

  String s = "Hello123World";

  String regex = "\\d";

  String s2 = s.replaceAll(regex, "");

5,  分组功能

  捕获组可以通过从左到右计算其开括号来编号,((A)(B(C)))存在4个这样的组

  1  ((A)(B(C)))

  2  (A)

  3  (B(C))

  4    (C)

  应用:叠词切割:"sdqqfgkkkhjppppkl";

  String regex = "(.)\\1+"; String[] arr = s.split(regex);

  应用:把字符串"我我....我...我.我...要要...要学....学学..学.编.编编.编.程...程程...程"输出为"我要学编程"

  String s = "我我....我...我.我...要要...要学....学学..学.编.编编.编.程...程程...程";

  String s2 = s.replaceAll("\\.+", "");

  String s3 = s2.replaceAll("(.)\\1+", "$1");

6, Pattern和Matcher

  Pattern p = Pattern.compile(a*b);  //获取到正则表达式

  Matcher m = p.matcher("aaaaaab");  //获取匹配器

  boolean b = m.matches();  //看是否能匹配,匹配就返回true

   等价于System.out.println("aaaaaab".matches("a*b"));

  应用:获取字符串中的电话号码

  String s = "我的电话号码是18988888888,曾经用过18987654321,还用过18812345678";

  String regex = "1[3578]\\d{9}";

  Pattern p = Pattern.compile(regex);

  Matcher m = p.matcher(s);

  while(m.find()) System.out.println(m.group()); //必须先find再group

java正则表达式

原文:https://www.cnblogs.com/kindleheart/p/8903933.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!