Let's say i have a string like this: "/c1/client/{clientId}/field/{fieldId}/version/{versionId}/file/{filename}"
I want to replace all values inside curly brackets with the actual values, so the link would look like this:
"c1/client/Tudor/field/search/version/1/file/hello.txt".
How can i do that in a way that does not limit the number of parameters used? Because i have some requests with 4 parameters (like this one) and others with only one parameter, or none. What is the best way to do this?
Edit: I would need something like: Search string for any values between {}. If string contains {value}, take all {values} and replace with parameter.
You can parse #pathParameters and redirect to the address you create with spring #controller. If these are request as you wrote that is the right approach.
In case of String:
var u = "/c1/client/{clientId}/field/{fieldId}/version/{versionId}/file/{filename}";
u.replace(/\{clientId\}/, "Tudor").replace(/\{fieldId\}/, "search").replace(/\{versionId\}/, 1).replace(/\{filename}/, "hello.txt");
You can try this
String str = "/c1/client/{clientId}/field/{fieldId}/version/{versionId}/file/{filename}";
Map<String, String> map = new HashMap<String, String>();
map.put("clientId", "Tudor");
map.put("fieldId", "search");
map.put("versionId", "1");
map.put("filename", "hello.txt");
for (Map.Entry<String, String> entry : map.entrySet()) {
str = str.replace("{" + entry.getKey() + "}", entry.getValue());
}
String newStr = str.substring(1);
System.out.println(newStr);
Related
I have this String
String tst = " {"id":$.id, "parent_id":200}";
I am trying to extract $.id from this string and replace it by an other word.
For now I tried:
tst = tst.replaceAll("(\\$.).", "other_word");
But this code is replacing all the rest (like "parent_id"...) by this other word
here is the output:
{"id":other_wordd_mag, "parent_id":200}
it's replacing only the "i" from "id_mag" any solution ?
This code seems to be replacing as expected:
String tst = " {\"id\":$.id, \"parent_id\":200}";
System.out.println(tst.replaceAll("\\$\\.id", "other_word"));
Output:
{"id":other_word, "parent_id":200}
Update
If you need to substitute some variables inside JSON, you can use the following regexp:
String tst = "{\"id\":$.id, \"name\":$.name, \"parent_id\":200}";
System.out.println(tst.replaceAll("(\\$\\.\\w+)", "\"other_word\"")); // using shorthand for word characters
output:
{"id":"other_word", "name":"other_word", "parent_id":200}
Or, if you have a map of variables in the form of key-value pairs, you can use this method:
static String replaceVars(String src, Map<String, String> vars) {
for (Map.Entry<String, String> e : vars.entrySet()) {
src = src.replaceAll("(\\$\\." + e.getKey()+ ")", "\"" + e.getValue()+"\"");
}
return src;
}
// -----------
String tstDiff = "{\"id\":$.id, \"name\":$.name, \"parent_id\":200}";
System.out.println(replaceVars(tstDiff, Map.of("id", "my_id", "name", "my_name")));
output:
{"id":"my_id", "name":"my_name", "parent_id":200}
Working with these types of strings can be a little bit easier if you know what JSON is.
And Java has also a really good library for handling Json strings called GSON.
You can use this library and for this specific case use the fromJson method.
But if you want to work with regex and get familiar with Strings:
tst.replaceAll("\\$\\.id", "other_word")
This should work properly.
In Java, I have to insert strings value based on the key in main string.
For example -
Main String -
sellers(seller: $sellerId, shipment: $shipmentId)
Map of key and value -
{
sellerId: abc
shipmentId: 123
}
So after inserting it will become
sellers(seller: abc, shipment: 123)
I know i can do string replace. But that doesn't seem to be good approach here. So just wondering is there a standard approach or better way of doing things here?
Two approaches you can consider:
1 - loop over map entries, and do a simple string replace (note that this assumes a single occurrence of each var in the strings; if that is not the case, you need to use replaceAll):
String text = "sellers(seller: $sellerId, shipment: $shipmentId)";
Map<String, Object> binding = ...;
String result = text;
for (Entry<String, Object> entry : binding.entrySet()) {
result = result.replace("$" + entry.getKey(), String.valueOf(entry.getValue()));
}
2 - for advanced use cases, you want to use a proper template engine. And here's an example using groovy's simple template engine (use in java by adding the groovy jar):
groovy.text.SimpleTemplateEngine engine = new groovy.text.SimpleTemplateEngine();
Writable template = engine.createTemplate(text).make(binding);
String result = template.toString();
Just note that groovy replaces variable names prefixed with $, and that's why this works without changes (making this a good choice for your current syntax).
Both produce your expected result, but you have to choose based on what this can turn into.
Depending on values map can hold you may face some problems. For instance if value may contain other key identifier like
{
foo: $bar
bar: 123
}
then using series of replace(mapEntryKey, mapEntryValue) could change string like
abc $foo efg $bar
first into $foo->$bar
abc $bar efg $bar
and then $bar->123
abc 123 efg 123
which is NOT what we wanted.
To avoid such problem we should iterate over template only once, search for each $key and replace it with value stored for it in map. If map doesn't contain such key we can leave it as it (replace it with itself).
We can do it with Matcher#replaceAll(Function<MatchResult,String> replacer). BTW if map value can contain $ and \ which are also metacharacters in replacement, we need to escape them. To do it we can use Mather#quoteReplacement method.
Demo:
Map<String, String> map = Map.of("sellerId", "abc",
"shipmentId", "123");
String yourTemplate = "sellers(seller: $sellerId, shipment: $shipmentId)";
Pattern p = Pattern.compile("\\$(\\w+)");
Matcher m = p.matcher(yourTemplate);
String replaced = m.replaceAll(match -> {
if(map.containsKey(match.group(1))){
return Matcher.quoteReplacement(map.get(match.group(1)));
}else{
return Matcher.quoteReplacement(match.group());
}
});
System.out.println(replaced);
Output: sellers(seller: abc, shipment: 123).
String format is an option here
Map<String, Integer> yourMap = new HashMap<>();
yourMap.put("abc", 123);
for (Map.Entry<String, Integer> entry : yourMap.entrySet()) {
String output = String.format("sellers(seller: %s, shipment: %d)", entry.getKey(), entry.getValue());
System.out.println("output = " + output);
}
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 😁
This question already has answers here:
How to convert HashMap to json Array in android?
(5 answers)
Closed 5 years ago.
I am developing an Android app in which I have to send LinkedHashMap results by API but the problem what I am getting is format of result is different. How can I put keys and values both in inverted commas?
I'm getting result like this:
list: {0=816444014066, 1=747083010945, 2=816444010969}
And I want result like this:
list: {"0" : "816444014066","1" : "747083010945","2" : "816444010969"}
How to change the format of result?
Use My Answer. It worked for me.
LinkedHashMap<String, String> data = new LinkedHashMap<String, String>();
// Instantiate a new Gson instance.
Gson gson = new Gson();
// Convert the ordered map into an ordered string.
String json = gson.toJson(data, LinkedHashMap.class);
// Print ordered string.
Log.e("list", ""+json); // {"0" : "816444014066","1" : "747083010945","2" : "816444010969"}
To get the quotes you need to make your keys and values String in your LinkedHashMap
Edit:
maybe what you need is already provided in this answer
In Java you can put quotes to String with :
String value = " \"1\" ";
You could do it like this:
Map<String, String> linkedmap = new LinkedHashMap<>();
linkedHashMap.put(setQuotes("1"), setQuotes("5445454"));
public static String setQuotes(String value){
String result = "";
if(!value.isEmpty()){
result = "\"" + value + "\"";
}
return result;
}
If you print it in the console, it returns:
{"1"="5445454"}
I think that possibility is to create your own Map class that extends LinkedHashMap and to create and implement in it method with behavior similar to behavior of toString() method. This link might help you to get started with implementation of that method:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/AbstractMap.java#AbstractMap.toString%28%29
Hi I have a strange question about java. I will leave out the background info so as not to complicate it. If you have a variable named fname. And say you have a function returning a String that is "fname". Is there a way to say reference the identifier fname via the String "fname". The idea would be something like "fname".toIdentifier() = value but obviously toIdentifier isn't a real method.
I suppose a bit of background mite help. Basically I have a string "fname" mapped to another string "the value of fname". And I want a way to quickly say the variable fname = the value of the key "fname" from the map. I'm getting the key value pair from iterating over a map of cookies in the form . And I don't want to do "if key = "fname" set fname to "value of fname" because I have a ton of variables that need to be set that way. I'd rather do something like currentkey.toIdentifer = thevalue. Weird question maybe I'm overlooking a much easier way to approach this.
Why don't you just use a simple hashmap for this?
Map<String, String> mapping = new HashMap<String, String>();
mapping.put("fname", "someValue");
...
String value = mapping.get(key); //key could be "fname"
In a way you're describing what reflection is used for:
You refer to an object's fields and methods by name.
Java Reflection
However, most of the time when people ask a question like this, they're better off solving their problem by re-working their design and taking advantage of data structures like Maps.
Here's some code that shows how to create a Map from two arrays:
String[] keyArray = { "one", "two", "three" };
String[] valArray = { "foo", "bar", "bazzz" };
// create a new HashMap that maps Strings to Strings
Map<String, String> exampleMap = new HashMap<String, String>();
// create a map from the two arrays above
for (int i = 0; i < keyArray.length; i++) {
String theKey = keyArray[i];
String theVal = valArray[i];
exampleMap.put(theKey, theVal);
}
// print the contents of our new map
for (String loopKey : exampleMap.keySet()) {
String loopVal = exampleMap.get(loopKey);
System.out.println(loopKey + ": " + loopVal);
}
Here's a link to the JavaDoc for Map.