简体   繁体   English

Java8字符串replaceAll更改的行为

[英]Java8 String replaceAll changed behavior

I have this text = "$i $index" and this map: 我有此text = "$i $index"和此地图:

Map<String, String> vars = new HashMap<String, String>();

        vars.put("i","index0");
        vars.put("index","counter0"); 

The goal is to replace all keys with the relative values. 目标是用相对值替换所有键。
In this test the regex used in the replaceAll method is a result of a concatenation 在此测试中,replaceAll方法中使用的正则表达式是串联的结果

            firstTest();
            // first test results:
            // java 7: index0  counter0
            // java 8: index0  index0ndex

in this, the regex used in the replaceAll method is a complete string 在此,replaceAll方法中使用的正则表达式是一个完整的字符串

            secondTest();
            // second test resuls:
            // java 7: index0  index0ndex
            // java 8: index0  index0ndex

In this last, i compare the Pattern.quote method with strings concatenated and the same strings complete 最后,我将Pattern.quote方法与串联的字符串进行比较,并完成相同的字符串

            thirdTest();
            // third test results:
            // java 7: first: \Q$index\E second: \Q$index\E are equals: true
            // java 8: first: \Q$index\E second: \Q$index\E are equals: true

First test code: 第一个测试代码:

private static void firstTest() {
    Map<String, String> vars = new HashMap<String, String>();

    vars.put("i","index0");
    vars.put("index","counter0");

    String text = "$i  $index";

    for (Entry<String, String> var : vars.entrySet())
        text = text.replaceAll(Pattern.quote("$"+var.getKey()), var.getValue());

    System.out.println(text);
}

Second test code: 第二测试代码:

private static void secondTest() {
    Map<String, String> vars = new HashMap<String, String>();

    vars.put("$i","index0");
    vars.put("$index","counter0");

    String text = "$i  $index";

    for (Entry<String, String> var : vars.entrySet())
        text = text.replaceAll(Pattern.quote(var.getKey()), var.getValue());

    System.out.println(text);
}

Third test code: 第三次测试代码:

private static void thirdTest() {
    Map<String, String> vars = new HashMap<String, String>();
    vars.put("index","counter0");

    String firstQuote = Pattern.quote("$"+vars.keySet().toArray()[0]);
    String secondQuote = Pattern.quote("$index");

    System.out.println("first: " + firstQuote + " second: " + secondQuote 
                     + " are equals: " + firstQuote.equals(secondQuote));

}

Can someone explain why I get such different results? 有人可以解释为什么我得到如此不同的结果吗?

Variation in the output would be due to order of iteration. 输出的变化将归因于迭代的顺序。

while iterating over vars if you get $i first then in text string both $i and $i in $index gets replaced. 在迭代vars时,如果先获取$i然后替换文本字符串$i$index $ i。 in the second iteration nothing will get replaced as it didn't find any '$index' in the string. 在第二次迭代中,不会在字符串中找到任何“ $ index”,因此不会替换任何内容。

If you can debug your code you can find the answer for that. 如果可以调试代码,则可以找到答案。 To get the values in some sorted order use LinkedHashMap (kept in insertion order) or TreeMap, sortedMap (Custom order as designed by you) 要以某种排序顺序获取值,请使用LinkedHashMap(按插入顺序保留)或TreeMap,sortedMap(由您设计的自定义顺序)

java.util.HashMap is unordered; java.util.HashMap是无序的; you can't and shouldn't assume anything beyond that. 您不能也不应承担任何其他事情。

This class makes no guarantees as to the order of the map; 此类无法保证地图的顺序。 in particular, it does not guarantee that the order will remain constant over time. 特别是,它不能保证顺序会随着时间的推移保持恒定。

java.util.LinkedHashMap uses insertion-order. java.util.LinkedHashMap使用插入顺序。

This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. 此实现与HashMap的不同之处在于,它维护贯穿其所有条目的双向链接列表。 This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). 此链表定义了迭代顺序,通常是将键插入映射的顺序(插入顺序)。

java.util.TreeMap, a SortedMap, uses either natural or custom ordering of the keys. java.util.TreeMap(SortedMap)使用键的自然顺序或自定义顺序。

The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. 根据映射键的自然顺序或在映射创建时提供的Comparator对映射进行排序,具体取决于所使用的构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM