例子
- package intro.regex;
-
-
import java.util.regex.Matcher;
-
import java.util.regex.Pattern;
-
-
public class RegexTest {
-
-
public static void main(String [] args){
-
Pattern pattern = Pattern.compile("a.*string");
-
Matcher matcher = pattern.matcher("a string");
-
-
boolean didMatch = matcher.matches();
-
System.out.println(didMatch); //true
-
-
int patternStartIndex = matcher.start(); //0
-
int patternEndIndex = matcher.end(); //8
-
System.out.println("Start:" + patternStartIndex + " end: " + patternEndIndex);
-
-
matcher = pattern.matcher("a string with more than just the pattern");
-
didMatch = matcher.matches();
-
System.out.println(didMatch); //false
-
matcher = pattern.matcher("a string with more than just the pattern");
-
didMatch = matcher.lookingAt();
-
System.out.println(didMatch); //true
-
-
pattern = Pattern.compile("[A-Z][a-z]*([A-Z][a-z]*)+");
-
matcher = pattern.matcher("Here is a WikiWord followed by AnotherWikiWord, then YetAnotherWikiWord.");
-
while(matcher.find()){
-
System.out.println("Found whit wiki word: " + matcher.group());
-
//Found whit wiki word: WikiWord
-
//Found whit wiki word: AnotherWikiWord
-
//Found whit wiki word: YetAnotherWikiWord
-
}
-
-
System.out.println("*******************************************************");
-
matcher.reset();
-
StringBuffer buffer = new StringBuffer();
-
while(matcher.find()){
-
matcher.appendReplacement(buffer, "blah$0blah");
-
System.out.println(buffer.toString());
-
//Here is a blahWikiWordblah
-
//Here is a blahWikiWordblah followed by blahAnotherWikiWordblah
-
//Here is a blahWikiWordblah followed by blahAnotherWikiWordblah, then blahYetAnotherWikiWordblah
-
}
-
matcher.appendTail(buffer);
-
System.out.println(buffer.toString());
-
//Here is a blahWikiWordblah followed by blahAnotherWikiWordblah, then blahYetAnotherWikiWordblah.
-
System.out.println("*******************************************************");
-
-
}
-
}
几个要点:
1. Matcher.end()方法获得匹配到的子字符串的最后一个字符在字符串中的索引位置+1.
2. lookingAt()方法是从第一个字符看是不是有匹配的字符串,即使有匹配的,但不是从第一个字符开始,也不能匹配成功,如:
- Pattern pattern = Pattern.compile("a.*string");
- Matcher matcher = pattern.matcher("a string");
-
- matcher = pattern.matcher("a string with more than just the pattern");
- boolean didMatch = matcher.matches();
- System.out.println(didMatch); //false
- matcher = pattern.matcher("a string with more than just the pattern");
- didMatch = matcher.lookingAt();
- System.out.println(didMatch); //true
- matcher = pattern.matcher("Here is a string with more than just the pattern");
- didMatch = matcher.lookingAt();
- System.out.println(didMatch); //false
阅读(1127) | 评论(0) | 转发(0) |