正则表达式
*零次或多次
+一次或多次
\s 一个或多个空格
\d+一个或多个数字
\. . ()? 括号内可选
Pattern Matcher PatternSyntaxException
replaceFirst 和replaceAll 区别
replaceFirst 替换首次匹配,replaceAll 替换所有匹配。
String word="cat";
String string = "cat cat cat cattie cat";
findWord(string,word);
matches 和 looking at 区别
matches 要求整个序列都匹配,而lookingAt 不要求。
lookingAt 方法虽然不需要整句都匹配,但是需要从第一个字符开始匹配。
String REGEX2 = "foo";
String INPUT1 = "fooooooooooooooooo";
String INPUT2 = "ooooofoooooooooooo";
Pattern pattern;
Matcher matcher;
Matcher matcher2;
pattern = Pattern.compile(REGEX2);
matcher = pattern.matcher(INPUT1);
matcher2 = pattern.matcher(INPUT2);
System.out.println("Current REGEX is: "+REGEX2);
System.out.println("Current INPUT is: "+INPUT1);
System.out.println("Current INPUT2 is: "+INPUT2);
System.out.println("lookingAt(): "+matcher.lookingAt());
System.out.println("matches(): "+matcher.matches());
System.out.println("lookingAt(): "+matcher2.lookingAt());
replaceFirst 和replaceAll 区别
replaceFirst 替换首次匹配,replaceAll 替换所有匹配。
String REGEX = "dog";
String INPUT = "The dog says meow. " +"All dogs say meow."; String REPLACE = "cat";
Pattern p = Pattern.compile(REGEX);
// get a matcher object
Matcher m = p.matcher(INPUT);
INPUT = m.replaceAll(REPLACE);
System.out.println(INPUT);
appendReplacement 和 appendTail 方法
String REGEX = "a*b";
String INPUT = "aabfooaabfooabfoobkkk";
String REPLACE = "-";
Pattern p = Pattern.compile(REGEX);
// 获取 matcher 对象
Matcher m = p.matcher(INPUT);
StringBuffer sb = new StringBuffer();
while(m.find()){
m.appendReplacement(sb,REPLACE);
}
m.appendTail(sb);
System.out.println(sb.toString());
System.out.println();
String str3 = "account=? and uu =? or n=?";
System.out.println("多个分隔符返回值 :" );
for (String retval: str3.split("and|or")){
System.out.println(retval); }