2014-01-16 170 views
0

我想用它们的一个哈希来替换一个字符串的所有匹配的子字符串。Java:用一个字符串替换所有匹配的字符串子串

可以说我有这样的

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

字符串现在我想替换所有匹配字符串正则表达式(例如这里“([A-FA-F \ d {5} )“)与他们的哈希值。

假定有是获取作为参数刺法的子字符串并将其返回值SHA1

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

我怎样才能找到所有匹配的子串,并与他们的哈希取代他们?

+0

那么,你有什么尝试? – Keppil

+1

看看Matcher类。你会在这里使用两个相关的方法。 –

+2

'find','appendReplacement','appendTail'。 –

回答

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(); 

} 
相关问题