Java:用字符串替换字符串的所有匹配子字符串

时间:2014-01-16 11:45:49

标签: java regex replace substring

我想用散列它们来替换字符串的所有匹配子串。

假设我有一个像这样的字符串

String myString = "This is a A1B4F string with some 342BF matches FFABC that should be replaced.";

现在我想将所有匹配的字符串替换为regex(例如这里“([a-fA-F \ d] {5})”)及其散列值。

假设有一个sting方法将子字符串作为参数获取并返回其sha1值

public static String giveMeTheSha1Of(String myClearText){
    return ....; (the sha1 value of the string)
}

如何找到所有匹配的子字符串,并用它们的哈希值替换它们?

1 个答案:

答案 0 :(得分:1)

谢谢Rohit Jain和Marko Topolnik。根据您的意见,我找到了我要搜索的内容。

public static String replace5CharHex(String input){

    String REGEX = "([a-fA-F\\d]{5})";
    String tmpSubstring = "";

    Pattern p = Pattern.compile(REGEX);
    Matcher m = p.matcher(input);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {

        tmpSubstring = hashManager.createNewHash(m.group());
        m.appendReplacement(sb, tmpSubstring);
    }
    m.appendTail(sb);

    return sb.toString();

}
相关问题