2012年8月15日 星期三

Regular Expression - Java

Replace All
String s = "Let's replace Cat with another Cat";
s.replaceAll("Cat", "Dog");
---> "Let's replace Dog with another Dog"

Replace All ignore case
s.replaceAll("(?i)cat", "dog");
---> "Let's replace dog with another dog" 

Multiple replacement
s.replaceAll("(?i)Let's replace (.*?) with another (.*?)", " $1 is replaced by $2 ");
--> "Cat is replaced by Cat"


Case-insensitive match

// Case insensitive for ASCII
Pattern p = Pattern.compile("TheRegex", Pattern.CASE_INSENSITIVE);

// Case insensitive for Unicode
Pattern p = Pattern.compile("TheRegex", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher m = p.matcher(StrToBeMatched);
if(m.find()){
  for( int i=0;i<=m.groupCount();i++){
    System.out.println(i+": "+ m.group(i)); 
  }
}

沒有留言:

張貼留言