[笔记]-正则

12-31重新整理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
String str = "2099-12-22";
String pat = "\d{4}-\d{2}-\d{2}";

Pattern p = Pattern.compile(pat);
// 实例化Matcher类
Matcher m = p.matcher(str);

if (m.matches()) System.out.println("日期格式合法!");

String newString = m.replaceAll("_");

String str2 = "1234567890";
Pattern.compile("[0-9]+").matcher(str2).matches();

// String类有三个方法支持正则操作
String str3 = "A1B22C333D4444E55555F".replaceAll("\d+", "_");
boolean temp = "1888-07-27".matches("\d{4}-\d{2}-\d{2}");
String s[] = "A1B22C333D4444E55555F".split("\d+");
1
2
3
4
5
6
7
8
9
10
Matcher m = Pattern.compile("\w+").matcher("Java is shit!");
while (m.find()) {
System.out.println(m.group());
System.out.println(m.group() + "子串起始:" + m.start() + ",结束:" + m.end());
}
int i = 0;
while (m.find(i)) {
System.out.print(m.group() + "t");
i++;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
String[] msgs = { "Java has regular expressions in 1.4", 
"regular expressions now expressing in Java",
"Java represses oracular expressions" };

for (String msg : msgs) {
System.out.println(msg.replaceFirst("re\w*", "jj1"));
System.out.println(Arrays.toString(msg.split(" ")));
}

Pattern p = Pattern.compile("re\w*");
Matcher matcher = null;

for (int i = 0; i < msgs.length; i++) {
if (matcher == null) {
matcher = p.matcher(msgs[i]);
} else {
matcher.reset(msgs[i]);
}
System.out.println(matcher.replaceAll("gg2"));
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
String[] mails = { "[email protected]", "[email protected]", "[email protected]", "[email protected]" };

String mailRegEx = "\w{3,20}@\w+\.(com|org|cn|org|net|gov)";

Pattern mailPattern = Pattern.compile(mailRegEx);
Matcher matcher = null;

for (String mail : mails) {
if (matcher == null) {
matcher = mailPattern.matcher(mail);
} else {
matcher.reset(mail);
}
if (matcher.matches()) System.out.println(mail + "有效");
}