Java基于正则表达式实现查找匹配的文本功能【经典实例】

时间:2022-08-23 14:14:21

本文实例讲述了Java基于正则表达式实现查找匹配的文本功能。分享给大家供大家参考,具体如下:

REMatch.java:

?
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
package reMatch;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * Created by Frank
 */
public class REMatch {
  public static void main(String[] args) {
    String patt = "Q[^u]\\d+\\.";
    Pattern r = Pattern.compile(patt);
    String line = "Order QT300. Now! QT400.";
    Matcher m = r.matcher(line);
    while (m.find()) {
      // group(0)或group()将会返回整个匹配的字符串(完全匹配);group(i)则会返回与分组i匹配的字符
      // 这个例子只有一个分组
      System.out.println(patt + " matches \"" + m.group(0) + "\" in \"" + line + "\"");
      System.out.println("start:" + m.start() + " end:" + m.end());
/*
输出:
 
Q[^u]\d+\. matches "QT300." in "Order QT300. Now! QT400."
start:6 end:12
Q[^u]\d+\. matches "QT400." in "Order QT300. Now! QT400."
start:18 end:24
*/
    }
  }
}

eclipse运行结果如下图:

Java基于正则表达式实现查找匹配的文本功能【经典实例】

REMatchTwoFields.java:

?
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
package reMatchTwoFields;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * Created by Frank
 */
public class REMatchTwoFields {
  public static void main(String[] args) {
    String inputLine = "Adams,John Quincy";
    Pattern r = Pattern.compile("(.*),(.*)");
    Matcher m = r.matcher(inputLine);
    if (!m.matches()) {
      throw new IllegalArgumentException("Bad Input");
    }
    // 分组0得到的是整个原字符串
    for (int i = 0; i < m.groupCount() + 1; i++) {
      System.out.println("分组" + i + ":" + m.group(i));
/*
输出:
 
分组0:Adams,John Quincy
分组1:Adams
分组2:John Quincy
*/
    }
  }
}

eclipse运行结果如下图:

Java基于正则表达式实现查找匹配的文本功能【经典实例】

希望本文所述对大家java程序设计有所帮助。