简体   繁体   中英

Filter out unwanted string in map

EDIT:

I have string like this:

String value1 = "xyzz#@#$%helloworldtestdata"

or

String value1 = "xyzztestcase" or String value1 = "notincludedxyzztestcase"

and

String value2 = "xxxyz! xyyz xyzz xyyz"

I am trying to filter out each string with their corresponding word. So far, I have this code and it was fine but not with the value1

Map<String, String> map = new HashMap<String, String>();
    map.put("xxxyz!", "test1");
    map.put("xxxyz?", "test2");
    map.put("xyyz", "test3");
    map.put("xyzz", "test4");

    for (String s : map.keySet()) {
        if (value2.contains(s)) {
            value2 = value2.replaceAll(s, map.get(s));
        } 
    }

If I use the value2 here is the output I am getting:

test1 test3 test4 test3

But if I use the value1 I am getting this one:

test4#@#$%helloworldtestdata

How can I filter out the part that is not included on my map, key but not messing the spaces of value1?

The replaceAll method is simply taking whatever your value for s (the keys in your map) is and replacing it with your value for s in your map. From what you described, something similar to what you want to do is do a value2 = value2.replaceAll("#@#$%helloworldtestdata", "");

This will replace the string #@#$%helloworldtestdata with an empty one.

To do this reassignment in your method, you would want to add the following to your map: map.put("#@#$%helloworldtestdata", "test5"); (test5 is just an example)

Adding this will not mess up your spaces in value1 because the string it looking to replace (the regex) has not been changed for any of the other strings you are looking for.

i dont know about i use, but here i use in my code.

var = "how to set love"

i just use one set to get value i want. print var[:2]

is wil get "how"

and yes if you fil replace just use x = var.replace("i will be", "how to")

it will get "i will be set love"

correct me if i flase 😁

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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