Java經典例項:正規表示式,找到匹配的文字

FrankYou發表於2016-11-09
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

 

相關文章