在用到Mather進行替換的時候有3個總要的方法:
1、replaceAll(str) : 替換所有
2、replaceFirst(str): 替換第一次匹配到的
3、appendReplacement(stringbuffer,str) : 這是個經常用到的函數,第一個參數是傳入一個StringBuffer,第二個參數是要指定要用來替換的文本,該函數可以將替換後的字串合并到原字串中,配合appendTail(StringBuffer sb) 使用,達到我們想要的替換結果,即得到的字串中只替換我們想要替換的,其他的不變。
如例子1:
public void testReg(){String str1="ttttttttA\"B\"CA\"tttttttt";final String REGEXH1="A\"";Pattern pattern1 = Pattern.compile(REGEXH1,Pattern.CASE_INSENSITIVE+Pattern.DOTALL);Matcher matcher1 = pattern1.matcher(str1);StringBuffer sb = new StringBuffer();while(matcher1.find()){matcher1.appendReplacement(sb, "OO");} matcher1.appendTail(sb); System.out.println(sb.toString());}
例子2:
public void testReg2(){String str1="ABCDEFG";final String REGEXH1="ABC";Pattern pattern1 = Pattern.compile(REGEXH1,Pattern.CASE_INSENSITIVE+Pattern.DOTALL);Matcher matcher1 = pattern1.matcher(str1);StringBuffer sb = new StringBuffer();//在匹配到的字串中替換掉某個字元,如在匹配到的ABC中把B替換為@while(matcher1.find()){String matchStr = matcher1.group();matchStr = matchStr.replaceAll("B", "@");matcher1.appendReplacement(sb, matchStr);} matcher1.appendTail(sb); System.out.println(sb.toString());}
附:
Matcher方法如下:
Matcher |
appendReplacement(StringBuffer sb, String replacement) 將當前匹配子串替換為指定字串,並且將替換後的子串以及其之前到上次匹配子串之後的字串段添加到一個StringBuffer對象裡。 |
StringBuffer |
appendTail(StringBuffer sb) 將最後一次匹配工作後剩餘的字串添加到一個StringBuffer對象裡。 |
int |
end() 返回當前匹配的子串的最後一個字元在原目標字串中的索引位置 。 |
int |
end(int group) 返回與匹配模式裡指定的組相匹配的子串最後一個字元的位置。 |
boolean |
find() 嘗試在目標字串裡尋找下一個匹配子串。 |
boolean |
find(int start) 重設Matcher對象,並且嘗試在目標字串裡從指定的位置開始尋找下一個匹配的子串。 |
String |
group() 返回當前尋找而獲得的與組匹配的所有子串內容 |
String |
group(int group) 返回當前尋找而獲得的與指定的組匹配的子串內容 |
int |
groupCount() 返回當前尋找所獲得的匹配組的數量。 |
boolean |
lookingAt() 檢測目標字串是否以匹配的子串起始。 |
boolean |
matches() 嘗試對整個目標字元展開匹配檢測,也就是只有整個目標字串完全符合時才返回真值。 |
Pattern |
pattern() 返回該Matcher對象的現有匹配模式,也就是對應的Pattern 對象。 |
String |
replaceAll(String replacement) 將目標字串裡與既有模式相匹配的子串全部替換為指定的字串。 |
String |
replaceFirst(String replacement) 將目標字串裡第一個與既有模式相匹配的子串替換為指定的字串。 |
Matcher |
reset() 重設該Matcher對象。 |
Matcher |
reset(CharSequence input) 重設該Matcher對象並且指定一個新的目標字串。 |
int |
start() 返回當前尋找所獲子串的開始字元在原目標字串中的位置。 |
int |
start(int group) 返回當前尋找所獲得的和指定組匹配的子串的第一個字元在原目標字串中的位置。 |