RegexMatches.java 文件代碼:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
? ? public static void main( String args[] ){
? ? ? // 按指定模式在字符串查找
? ? ? String line = "This order was placed for QT3000! OK?";
? ? ? String pattern = "(\\D*)(\\d+)(.*)";
? ? ? // 創(chuàng)建 Pattern 對(duì)象
? ? ? Pattern r = Pattern.compile(pattern);
? ? ? // 現(xiàn)在創(chuàng)建 matcher 對(duì)象
? ? ? Matcher m = r.matcher(line);
? ? ? if (m.find( )) {
? ? ? ? System.out.println("Found value: " + m.group(0) );
? ? ? ? System.out.println("Found value: " + m.group(1) );
? ? ? ? System.out.println("Found value: " + m.group(2) );
? ? ? ? System.out.println("Found value: " + m.group(3) );
? ? ? } else {
? ? ? ? System.out.println("NO MATCH");
? ? ? }
? }
}
以上實(shí)例編譯運(yùn)行結(jié)果如下:
Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT
Found value: 3000
Found value: ! OK?
正則表達(dá)式語(yǔ)法
在其他語(yǔ)言中,\\ 表示:我想要在正則表達(dá)式中插入一個(gè)普通的(字面上的)反斜杠,請(qǐng)不要給它任何特殊的意義。
在 Java 中,\\ 表示:我要插入一個(gè)正則表達(dá)式的反斜線,所以其后