第一篇

基本语法

预定义字符类

符号 意思
. 任意一个非\字符
\d 字母,数字,下划线,汉字
\s 任意空白字符
\D 非数字
\S 非空白数字
\w 单词字符(字母,数字)
\W 非单词字符

字符次数

符号 意思
* 零次或者多次
+ 一次或多次
零次或一次
{n} n次
{n,} 大于n次
{n,m} n-m次

例:
^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+\\.[a-zA-Z0-9_-]+$
上面是一般邮箱的正则表达式。


Regular Expression Matching

leetCode No.10:
  判断pattern(P)是否匹配string(s)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//直接用 pattern(regex,input)????
public class RegularExpressionMatching {
/*
只考虑string的第一个能否在开头中找到匹配的,p有*时,要考虑前两个,其余的交给循环去做就行了。
*/
public boolean isMatch(String s, String p) {
if (p.isEmpty()) return s.isEmpty();
boolean firstMatch = (!s.isEmpty() && (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.'));

if (p.length() >= 2 && p.charAt(1) == '*') {
return (isMatch(s, p.substring(2)) || (firstMatch && isMatch(s.substring(1), p)));

} else {
return firstMatch && isMatch(s.substring(1), p.substring(1));
}

}

/*
按照顺序一个个0-i,0-j都测试能够匹配,用二位数组去记录能否被匹配到,测试数组中最后的点,缺点,如果不匹配也要走完全程(或许可以加个判断???)
优点:
*/
public boolean isMatch2(String s, String p) {
boolean T[][] = new boolean[s.length()+1][p.length()+1];

//初始化
T[0][0] = true;
for (int i = 1; i <= p.length(); i++) {
if (p.charAt(i - 1) == '*') {
T[0][i] = T[0][i - 2];
}
}
//空间换时间
for (int i = 1; i <= s.length(); i++) {
for (int j = 1; j <= p.length(); j++) {
if (s.charAt(i - 1) == p.charAt(j - 1) || p.charAt(j - 1) == '.') {
T[i][j] = T[i - 1][j - 1];
} else if (p.charAt(j - 1) == '*') {
T[i][j] = T[i][j - 2];
if (p.charAt(j - 2) == '.' || p.charAt(j - 2) == s.charAt(i - 1)) {
T[i][j]=T[i][j]|T[i-1][j];
}
}else{
T[i][j]=false;
}
}
}
return T[s.length()][p.length()];

}
public void test(){
boolean rs=isMatch2("aa","a*");
System.out.println(rs);
}

public static void main(String[] args) {
RegularExpressionMatching r=new RegularExpressionMatching();
r.test();
}
}

没做出来,看的解题思路,主要的点在于把string一个一个字符的匹配,每个字符的匹配中可以分为两种情况

  1. 相同或者p为”.”;
  2. p下一个为“ ”,
    2.1.
    为0
    2.2. 为1;只考虑单个字符,大于等于2等下一轮判断

java.util.regex包

  有两个类Matcher和Pattern

Matcher

常用方法:

  1. boolean matches()整个序列与模式匹配。
  2. boolean lookingAt()从开头进行匹配。
  3. boolean find()与该模式匹配的输入序列的下一个子序列。
    1
    2
    3
    4
    5
    Pattern p=Pattern.compile("a*b");
    Matcher m=P.matcher("aaaaaabef");
    boolean b=m.matches();//false,整个匹配。
    boolean c=m.find();//true,序列中有就行。
    boolean d=m.lookingAt();//true,开头有字符匹配就行。
Pattern

正则表达式的编译表示形式,首先编译为此类的实例,模式用来创建Matcher对象,对象就可以与字符序列匹配

1
2
3
Pattern p=Pattern.compile("a*b");
Matcher m=P.matcher("aaaaaab");
boolean b=m.matches();

Pattern.matcher(String regex,CharSequence input)等价

方法:

  1. String[] split(CharSequence input)通过正则分割字符序列
  2. String pattern()返回原来的表达式