1. 量词的小细节,贪婪与懒惰
2. find()/find(i)方法
3. (?m) 单行模式 :标记的作用及用法(了解,用到时扩展)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestRegex {
public static void main(String[] args) {
String str = "abcabcabc";
System.out.println(str.replaceFirst("(abc)+", "---")); //abc出现一次或多次
System.out.println(str.replaceFirst("abc+", "---")); //ab后面的C出现一次或多次
System.out.println(str.replaceFirst("\\S+?", "---")); //贪婪模式,尽力匹配
System.out.println(str.replaceFirst("\\S+", "---")); //懒惰模式, 最少匹配
StringBuilder sb = new StringBuilder();
Matcher m = Pattern.compile("\\w+").matcher("Evening is full of the linnet's wings");
while(m.find()) {
sb.append(m.group()).append(" ");
}
System.out.println(sb.toString());
sb.setLength(0);
int i = 0;
while(m.find(i)) { //设置find的起点
sb.append(m.group()).append(" ");
i++;
}
System.out.println(sb.toString());
sb.setLength(0);
String str2 = "i have a big ice\n" +
"you not have ice\n";
//(?m)启动单行模式,此时^$符号表示每行的开头结尾,而不是整个字符串的开头结尾
Matcher m2 = Pattern.compile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$").matcher(str2);
while(m2.find()) {
for(int j=0; j<=m2.groupCount(); j++) {
sb.append("[").append(m2.group(j)).append("]");
}
System.out.println(sb.toString());
sb.setLength(0);
}
//find matches lookingAt区别
}
}
//output
---
---abcabc
---bcabcabc
---
Evening is full of the linnet s wings
Evening vening ening ning ing ng g is is s full full ull ll l of of f the the he e linnet linnet innet nnet net et t s s wings wings ings ngs gs s
[a big ice][a][big ice][big][ice]
[not have ice][not][have ice][have][ice]
4. appendReplacement() 、appendTail()
5.reset()
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestRegex2 {
public static void main(String[] args) {
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in cat the cat yard cat");
StringBuffer sb = new StringBuffer();
int i = 0;
while (m.find()) {
if (i % 2 == 0) {
m.appendReplacement(sb, "dog");
}
i++;
}
m.appendTail(sb);
System.out.println(sb.toString());
sb.setLength(0);
// reset()重新matcher字符串
m.reset("one cat two cats in the yard");
while (m.find()) {
m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
System.out.println(sb.toString());
}
}
//output
one dog two cats in dog the cat yard dog
one dog two dogs in the yard