java regular expression

1, [abc] a, b or c

       [^abc] Any character except a, b or c

  [a-zA-Z] a to z or A to Z, both inclusive

  [ad[mp]] a to d or m to p: [a-dm-p] (union)

  [az&&[def]] d, e or f (intersection)

2, * any character

  \d Digits: [0-9]

  \D Not a number: [^0-9]

  \s whitespace character: [\t\n\x0B\f\r]

  \S non-whitespace characters: [^\s]

  \w word character: [a-zA-Z_0-9]

  \W non-word character: [^\w]

3. Greedy Quantifier

  X? once or not at all

  X* zero or more times

  X+ one or more times

  X{n} exactly n times

  X{n,} at least n times

  X{n, m} at least n times, but not more than m times string

4. Replacement function

  String s = "Hello123World";

  String regex = "\\d";

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

5. Grouping function

  Capture groups can be numbered by counting their opening brackets from left to right, ((A)(B(C))) there are 4 such groups

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

  2  (A)

  3  (B(C))

  4    (C)

  Application: Redundant word cutting: "sdqqfgkkkhjppppkl";

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

  Application: put the string "I I....I...I.I...want...to learn....learn to learn..learn.edit.edit.program.program... Chengcheng...cheng" output is "I want to learn programming"

  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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324614069&siteId=291194637