9 //^q表示以q开头的,其中^字符在这个上下文中表示以...开头。
10 //[^u]表示所有不是u的字符都合法, 在[^ ]上下文中,^表示取非。
11 //\.表示dot的原意,因为该字符为meta字符,表示任意字符,加上
12 //转义符之后就只是表示原意了。
13 String pattern = "^q[^u]\\d+\\.";
14 String input = "QA777. is the next flight. It is on time.";
15 Pattern reCaseInsens = Pattern.compile(pattern,Pattern.CASE_INSENSITIVE);
16 Pattern reCaseSens = Pattern.compile(pattern);
17 Matcher m = reCaseInsens.matcher(input); // will match any case
18 boolean found = m.lookingAt(); // will match any case
19 System.out.println("IGNORE_CASE match " + found);
20 m = reCaseSens.matcher(input); // Get matcher w/o case-insens flag
21 found = m.lookingAt(); // will match case-sensitively
22 System.out.println("MATCH_NORMAL match was " + found);
23 }
24 /* 输出结果如下:
25 Name: Bananas
26 Number: 123
27 IGNORE_CASE match true
28 MATCH_NORMAL match was false
29 */
复制代码
2) 利用正则表达式拆分字符串到字符串数组:
1 public static void main(String[] args) {
2 String[] x = Pattern.compile("ian").split("the darwinian devonian explodian chicken");
3 for (int i = 0; i < x.length; i++) {
4 System.out.println(i + " \"" + x[i] + "\"");
5 }
6 }
7 /* 输出结果如下:
8 0 "the darwin"
9 1 " devon"
10 2 " explod"
11 3 " chicken"
12 */
复制代码
3) 在String中应用正则表达式:
1 public static void main(String[] args) {
2 String pattern = ".*Q[^u]\\d+\\..*";
3 String line = "Order QT300. Now!";
4 if (line.matches(pattern)) {
5 System.out.println(line + " matches \"" + pattern + "\"");
6 } else {
7 System.out.println("NO MATCH");
8 }
9 }
10 /* 输出结果如下:
11 Order QT300. Now! matches ".*Q[^u]\d+\..*"
12 */
复制代码
4) 正则表达式和CharSequence:
1 public class TestMain {
2 public static void testSearchAndReplace() {
3 Pattern p = Pattern.compile("(i|I)ce");
4 String candidateString = "I love ice. Ice is my favorite. Ice Ice Ice.";
5
6 Matcher matcher = p.matcher(candidateString);
7 String tmp = matcher.replaceFirst("Java");
8 System.out.println(tmp);
9 }
10 public static void testSearchAndReplace() {
11 CharSequence inputStr = "a b c a b c";
12 String patternStr = "a";
13 String replacementStr = "x";
14 // 将inputStr中所有的a替换为x
15 Pattern pattern = Pattern.compile(patternStr);
16 Matcher matcher = pattern.matcher(inputStr);
17 String output = matcher.replaceAll(replacementStr);
18 System.out.println(output);
19 }
20 private static void testNormalSearch() {
21 String patternStr = "b";
22 Pattern pattern = Pattern.compile(patternStr);
23 CharSequence inputStr = "a b c b";
24 Matcher matcher = pattern.matcher(inputStr);
25 boolean matchFound = matcher.find();
26 System.out.println(matchFound);
27 //group()将返回find()找到的匹配字符串,可以将其视为s.substring(m.start(), m.end())
28 String match = matche