正则表达式:其实一种规则,有自己特殊的应用,其作用就是针对于字符串进行操作

正则:就是用于操作字符串的规则,其中这些规则使用了一些字符表示。

 

1正则表达式的符号

 

 

预定义字符类

 

.

任何字符(与行结束符可能匹配也可能不匹配)

 

\d

数字:[0-9]

 

\D

非数字: [^0-9]

 

\s

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

 

\S

非空白字符:[^\s]

 

\w

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

 

\W

非单词字符:[^\w]

 

System.out.println("a".matches("."));

System.out.println("1".matches("\\d"));

System.out.println("%".matches("\\D"));

System.out.println("\r".matches("\\s"));

System.out.println("^".matches("\\S"));

System.out.println("a".matches("\\w"));

 

 

 

Greedy 数量词

 

X?

X,一次或一次也没有

X*

X,零次或多次

X+

X,一次或多次

X{n}

X,恰好n

X{n,}

X,至少n

X{n,m}

X,至少n次,但是不超过m

System.out.println( "a".matches(".") );

System.out.println( "a".matches("a") );

System.out.println("a".matches("a?") );

System.out.println( "aaa".matches("a*") );

System.out.println( "".matches("a+") );

System.out.println( "aaaaa".matches("a{5}") );

System.out.println( "aaaaaaaaa".matches("a{5,8}") );

System.out.println( "aaa".matches("a{5,}") );

System.out.println( "aaaaab".matches("a{5,}") );

 

 

 

范围表示

 

 

[abc]

ab c(简单类)

[^abc]

任何字符,除了 ab c(否定)

[a-zA-Z]

a z A Z,两头的字母包括在内(范围)

[a-d[m-p]]

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

[a-z&&[def]]

de f(交集)

[a-z&&[^bc]]

a z,除了 b c[ad-z](减去)

[a-z&&[^m-p]]

a z,而非 m p[a-lq-z](减去)

 

 

System.out.println( "a".matches("[a]") );

System.out.println( "aa".matches("[a]+") );

System.out.println( "abc".matches("[abc]{3,}") );

System.out.println( "abc".matches("[abc]+") );

System.out.println( "dshfshfu1".matches("[^abc]+") );

System.out.println( "abcdsaA".matches("[a-z]{5,}") );

System.out.println( "abcdsaA12".matches("[a-zA-Z]{5,}") );

System.out.println( "abcdsaA12".matches("[a-zA-Z0-9]{5,}") );

System.out.println( "abdxyz".matches("[a-c[x-z]]+"));

System.out.println( "bcbcbc".matches("[a-z&&[b-c]]{5,}"));

System.out.println( "tretrt".matches("[a-z&&[^b-c]]{5,}"));

 

 

2 匹配功能

 

 

需求:校验QQ号,要求:必须是5~15位数字,0不能开头。没有正则表达式之前

 

 

 1 public static void checkQQ(String qq)
 2     {
 3         int len = qq.length();
 4         if(len>=5 && len <=15)
 5         {
 6             if(!qq.startsWith("0"))
 7             {
 8                 try
 9                 {
10                     long l = Long.parseLong(qq);
11                     System.out.println("qq:"+l);
12                 }        
13                 catch (NumberFormatException e)
14                 {
15                     System.out.println("出现非法字符");
16                 }
17             }
18             else
19                 System.out.println("不可以0开头");
20         }
21         else
22             System.out.println("QQ号长度错误");
23     }
View Code

相关文章:

  • 2021-11-03
  • 2021-11-22
  • 2021-11-23
  • 2021-10-29
  • 2021-07-01
  • 2021-08-01
  • 2021-06-04
  • 2022-12-23
猜你喜欢
  • 2022-02-08
  • 2022-12-23
  • 2022-12-23
  • 2021-10-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案