简体   繁体   中英

Custom format string : arguments in double brackets java

I am working on android project but I retrieve from a server a .xml file with all localisations strings. I face a problem because when the string can include an argument, this argument is set in double brackets like :

You have {{0}} dollar(s) on your account

I can't use the regular String.format() function. I don't really see how could I resolve this, should I create a custom formatter?

EDIT: The string can have more than one parameter

Thx

Use String.replace() instead of String.format().

You can also replace multiple parameters Like,

String s = "{{0}} is friend with {{1}}"; 
s = s.replace("{{0}}","ABC"); 
s = s.replace("{{1}}","PQR");

A more elegant way would be to use a Regex: {{((.*?)*?)}} , which I was using in c# .

https://regexr.com/3tkl9

This will allow you to extract the values as well.

Pattern pattern = Pattern.compile("{{((.*?)*?)}}");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
    // Other stuff, like extracting values
    String value = matcher.group(1)
    // Then you can just String.replace the matches.
}

To create a function with more parameters:

public String format(String input, String... args) {
    // To access an element use e.g. args[0];
}

A full working function might be something like this (didn't test):

public String format(String input, String... args) {
    Pattern pattern = Pattern.compile("{{((.*?)*?)}}");
    Matcher matcher = pattern.matcher(input);
    while (matcher.find()) {
        String value = matcher.group(1);
        // TODO: error handling
        int index = Integer.parseInt(value);
        if (index < args.length) {
            input.replace(matcher.group(), args[index]);
        }
    }
}

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