Java 替换除文本中的第一个字符串(如果hashmap中存在)以外的所有字符串

Java 替换除文本中的第一个字符串(如果hashmap中存在)以外的所有字符串,java,regex,Java,Regex,文本存储在字符串变量中,并由一些API处理,以提供一个存储键和值的hashmap。键是文本中的一些特定单词,value是一个新词,它将替换文本中的键。我必须处理文本,这样它将用hashmap中的值替换键,但我必须保持文本中键的第一个实例不变 问题: 我可以通过迭代hashmap并替换文本中的键来替换我正在执行的所有实例。我想让第一把匹配的钥匙保持原样 在字符串函数中,我看到的是replace、replaceAll、replaceFirst 我该如何处理这个案子 例如: 输入:示例[2]这是一个示

文本存储在字符串变量中,并由一些API处理,以提供一个存储键和值的hashmap。键是文本中的一些特定单词,value是一个新词,它将替换文本中的键。我必须处理文本,这样它将用hashmap中的值替换键,但我必须保持文本中键的第一个实例不变

问题: 我可以通过迭代hashmap并替换文本中的键来替换我正在执行的所有实例。我想让第一把匹配的钥匙保持原样

在字符串函数中,我看到的是replace、replaceAll、replaceFirst

我该如何处理这个案子

例如:

输入:示例[2]这是一个示例文本。这是一个示例文本[69-3]。这是一个样本[69-3]文本

hashmap:{sample=sImple,text=text2,[69-3]=somenum}

输出:示例[2]这是一个示例文本。这是一个简单的文本2[69-3]。这是一个简单的文本2 somenum

此外,关键字匹配用于整个单词,而不是子字符串。比如,如果文本中的name是键,姓氏是字符串,那么它就不应该匹配,sur“name”也不应该更改。我使用replaceAll而不是replace来进行替换

提前感谢。

以下内容

String input="Example [2] This is a sample text. This is a sample xtexty text [69-3]. This is a sample [69-3] textME text.";

        Map<String,String> map = new HashMap<String,String>();
        map.put("sample","sImple");
        map.put("text","text2");
        map.put("[69-3]","somenum");

        for(Map.Entry<String, String> entry : map.entrySet()){
            input =input.replace(entry.getKey(),entry.getValue());
        input = input.replaceFirst(entry.getValue(), entry.getKey());
        Pattern p = Pattern.compile("(\\w+)*"+entry.getValue()+"(\\w+)|(\\w+)"+entry.getValue()+"(\\w+)*");
        Matcher matcher =  p.matcher(input);
       while( matcher.find()){
          int r =  matcher.group().indexOf(entry.getValue());
          int s =r+input.indexOf(matcher.group());
     input = input.substring(0,s)+entry.getKey()+input.substring(s+entry.getValue().length());
       }    
        }

        System.out.println(input);

    }

上面的代码不会替换子字符串,可以根据需要工作。

您可以找到第一次出现的索引,并替换该索引之后的所有内容。 因为我没有找到采用偏移参数的
replaceAll
,所以我可以建议您使用以下手工解决方案:


您可以使用正则表达式执行此操作

您的问题的答案已在本帖中给出:


我用replaceFirst和replaceAll解决了这个问题

创建一个dictionary2,它将包含与dictionary中相同的键,dictionary2中的值将是Key的修改版本

外汇:

字典:{sample=simple}

字典2:{sample=sample--A--}

然后使用replaceFirst将文本中字符串的第一个实例替换为dictionary2中的值


接下来替换文本中字符串的所有实例,使第一个实例保持原样,然后用dictionary2中的键替换修改后的第一个实例。

建立一个先前匹配键的列表(或集合,从技术上讲),仅替换匹配且存在于先前匹配集中的令牌。好的。。。我会试试这个方法。你试过我的答案吗?不,它不起作用。。。它只是没有替换文本中的字符串。输入和输出不是您所期望的吗?您能否提供您尝试过的输入和预期输出?我所显示的输出不是预期的?
  Example [2] This is a sample text. This is a sImple xtexty text2 [69-3]. This is a sImple somenum textME text2.
public static void replaceAllButFirst(StringBuilder modifiedString, String match, String replacement) {
    int index = modifiedString.indexOf(match);
    int matchLength = match.length(), replacementLength = replacement.length();
    if (index == -1) return;
    index += matchLength;
    index = modifiedString.indexOf(match, index);
    while (index != -1) {
        modifiedString.replace(index, index + matchLength, replacement);
        index += replacementLength;
        index = modifiedString.indexOf(match, index);
    }
}