Java经典实例:正则表达式,找到匹配的文本

时间:2022-03-21 03:22:26
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);
int i = 0;
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
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