【问题标题】:Java: Replace all matching substrings of a string with their hashesJava:用它们的哈希替换字符串的所有匹配子字符串
【发布时间】:2014-01-16 11:45:48
【问题描述】:

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

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

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

现在我想用它们的哈希值替换所有匹配的字符串到正则表达式(例如这里的 "([a-fA-F\d]{5})" )。

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

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

我怎样才能找到所有匹配的子字符串,并用它们的哈希替换它们?

【问题讨论】:

  • 那么,你有什么尝试?
  • 查看Matcher 类。您将在这里使用两个相关的方法。
  • find, appendReplacement, appendTail.
  • 到目前为止我还没有开发出解决方案,但我唯一能做的就是将字符串分解为“单词”并重建它(如果一个单词匹配我会替换它)
  • 你能给出一些想要的输入和输出值吗?

标签: java regex replace substring


【解决方案1】:

感谢 Rohit Jain 和 Marko Topolnik。通过您的 cmets,我找到了我正在寻找的东西。

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    • 2017-01-16
    • 2017-01-23
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多