import java.util.regex.Pattern; /** * Created by Frank * 在Java中使用正規表示式:測試模式 */ public class RESimple { public static void main(String[] args) { String pattern = "^Q[^u]\\d+\\."; String[] input = {"QA777. is the next flight. It is on time.", "Quack, Quack, Quack!"}; Pattern p = Pattern.compile(pattern); for (String s : input) { /** * 在字串中匹配模式,從字串的首字母開始,或者之前已經成功呼叫該方法,則從未能符合前面匹配的第一個字元開始 */ boolean found = p.matcher(s).find(); System.out.println("'" + pattern + "' " + (found ? " matches '" : "doesn't match '") + s + "'"); } } }
輸出:
'^Q[^u]\d+\.' matches 'QA777. is the next flight. It is on time.' '^Q[^u]\d+\.' doesn't match 'Quack, Quack, Quack!'