2 回答

TA貢獻1783條經(jīng)驗 獲得超4個贊
您可以使用 2 個捕獲組并在替換中使用它們,其中匹配項_
將被替換為/
^([^_]+)_([^_]+)_
用。。。來代替:
$1/$2/
例如:
String regex = "^([^_]+)_([^_]+)_";
String string = "02_01_fEa3129E_my Pic.png";
String subst = "$1/$2/";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
String result = matcher.replaceFirst(subst);
System.out.println(result);
結(jié)果
02/01/fEa3129E_my Pic.png

TA貢獻2037條經(jīng)驗 獲得超6個贊
您當(dāng)前的解決方案幾乎沒有問題:
這是低效的——因為每個都replaceFirst需要從字符串的開頭開始,所以它需要多次迭代相同的起始字符。
它有一個錯誤- 因為第 1 點。當(dāng)從開始而不是最后修改的地方迭代時,我們可以替換之前插入的值。
例如,如果我們想兩次替換單個字符,每次都用Xlike abc->XXc在代碼 like 之后
String input = "abc";
input = input.replaceFirst(".", "X"); // replaces a with X -> Xbc
input = input.replaceFirst(".", "X"); // replaces X with X -> Xbc
Xbc我們將以instead of結(jié)尾XXc,因為第二個replaceFirst將替換為Xwith Xinstead of bwith X。
為避免此類問題,您可以重寫代碼以使用Matcher#appendReplacement和Matcher#appendTail方法,以確保我們將迭代輸入一次并可以用我們想要的值替換每個匹配的部分
private static String replaceNMatches(String input, String regex,
String replacement, int numberOfTimes) {
Matcher m = Pattern.compile(regex).matcher(input);
StringBuilder sb = new StringBuilder();
int i = 0;
while(i++ < numberOfTimes && m.find() ){
m.appendReplacement(sb, replacement); // replaces currently matched part with replacement,
// and writes replaced version to StringBuilder
// along with text before the match
}
m.appendTail(sb); //lets add to builder text after last match
return sb.toString();
}
使用示例:
System.out.println(replaceNMatches("abcdefgh", "[efgh]", "X", 2)); //abcdXXgh
添加回答
舉報