java正則表達式實例

import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
/*
boolean matches(String input, Pattern pattern):當輸入字符串和正則表達式要精確匹配時使用。換句話說,正則表達式必須完整地描述輸入字符串。
boolean matchesPrefix(String input, Pattern pattern):當正則表達式匹配輸入字符串起始部分時使用。(例如正則表達式abc 匹配abc1或abc2)
boolean contains(String input, Pattern pattern):當正則表達式要匹配輸入字符串的一部分時使用(即,它必須是一個子串)。
另外,在上面三個方法調用中,你還可以用PatternMatcherInput對象作爲參數替代String對象;這時,你可以從字符串中最後一次匹配的位置開始繼續進行匹配。當字符串可能有多個子串匹配給定的正則表達式時,用PatternMatcherInput對象作爲參數就很有用了。用PatternMatcherInput對象作爲參數替代String時,上述三個方法的語法如下:
boolean matches(PatternMatcherInput input, Pattern pattern)
boolean matchesPrefix(PatternMatcherInput input, Pattern pattern)
boolean contains(PatternMatcherInput input, Pattern pattern)
*/
public class Pat {
 public static void main(String[] args) {
  Pattern parttern=null;
  PatternCompiler compiler = new Perl5Compiler();
  try{
   parttern = compiler.compile("(t[aeio]n)//s//d{1,3}//.//d{1,3}//.//d{1,3}//.//d{1,3}",Perl5Compiler.CASE_INSENSITIVE_MASK);
   PatternMatcher matcher = new Perl5Matcher();
   String input  = "ffdstan 172.17.94.105fdsfds";
   if (matcher.contains(input, parttern)){
   //if (matcher.matches(input, parttern)){
    MatchResult result = matcher.getMatch();
    System.out.println("true./r/n"+result.group(1));
   }else{
    System.out.println("false");
   }
  
  }catch(Exception ex){
      ex.printStackTrace();
  }
 }
}

運行結果﹕
true.
tan
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章