Java 正则表达式
Pattern 类:
pattern 对象是一个正则表达式的编译表示。Pattern 类没有公共构造方法。要创建一个 Pattern 对象,你必须首先调用其公共静态编译方法,它返回一个 Pattern 对象。该方法接受一个正则表达式作为它的第一个参数。
Matcher 类:
Matcher 对象是对输入字符串进行解释和匹配操作的引擎。与Pattern 类一样,Matcher 也没有公共构造方法。你需要调用 Pattern 对象的 matcher 方法来获得一个 Matcher 对象。
PatternSyntaxException:
PatternSyntaxException 是一个非强制异常类,它表示一个正则表达式模式中的语法错误。
正则检测:
String content = "I am noob from runoob.com.";
String pattern = ".*runoob.*";
System.out.println(Pattern.matches(pattern, content));
正则匹配获取结果:
String line = "This order was placed for QT3000! OK?";
String pattern = "(\\D*)(\\d+)(.*)";
Matcher m = Pattern.compile(pattern).matcher(line); //要求整个序列都匹配
Matcher m = Pattern.compile(pattern).lookingAt(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");
}
正则替换:
String REGEX = "dog";
String INPUT = "The dog says meow. All dogs say meow.";
String REPLACE = "cat";
Matcher m = Pattern.compile(REGEX).matcher(INPUT);
System.out.println(m.replaceFirst(REPLACE)); //替换首次匹配
System.out.println(m.replaceAll(REPLACE)); //替换所有匹配
String REGEX = "a*b";
String INPUT = "aabfooaabfooabfoobkkk";
String REPLACE = "-";
Matcher m = Pattern.compile(REGEX).matcher(INPUT);
StringBuffer sb = new StringBuffer();
while(m.find()){
m.appendReplacement(sb,REPLACE);
}
System.out.println(sb.toString()); //-foo-foo-foo-
m.appendTail(sb);
System.out.println(sb.toString()); //-foo-foo-foo-kkk