如何参数化字符串并替换参数

How to parametrize a string and replace parameters

我有一个由最终用户输入的字符串,这个字符串的格式应该是 Showing {0} to {1} of {2},我想用我从后端计算的数字替换大括号中的参数。 就像它发生在属性文件中的字符串一样。
我该怎么做?

示例输入:

Showing {0} to {1} of {2} 

示例输出:

Showing 1 to 12 of 30

您可以使用 MessageFormat:

String userInput = "Showing {0} to {1} of {2}";
String result = MessageFormat.format(userInput, 1, 12, 30);

您可以使用String.format()

这是如何做到的

int a = 1;
int b = 12;
int c = 30;
String myFormattedString = String.format("Showing %d to %d of %d", a, b, c); 
// Value of myFormattedString is 'Showing 1 to 12 of 30'

您应该使用正则表达式来获取这些参数的值。

为此,您必须考虑以下代码示例:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

Pattern pattern = Pattern.compile("\d+");
Matcher matcher = p.matcher("Showing 1 to 12 of 30");


int[] numbers; 
int i = 0;
while(matcher.find()){
 numbers[i++] = Integer.parseInt(matcher.group());
}

所以现在所有这些数字都在一个 int[] 中。

像这样尝试正则表达式:

public static void main(String[] args) {
    String s = "Showing {0} to {1} of {2}";
    int arr[] = { 10, 20, 30 };
    s = s.replaceAll("(.*)(\d)(.*)(\d)(.*)(\d)", "" + arr[0] + ""
            + arr[1] + "" + arr[2]);
    System.out.println(s);
}

O/P :

Showing {10} to {20} of {30}

您可以使用 java.text.MessageFormat 包中的 MessageFormat,如下所示

public static void main(String[] args) {
        String a = "this is {0} of {1} another String";
        System.out.println(MessageFormat.format(a, "replacement1", "replacement2"));
    }

O/P "this is replacement1 of replacement2 another String"

如果你有多个参数和替换,你可以 String.format,但如果你只有一个参数要替换,你可以使用

String myselfUrl = https://url.abc/{cloudId}/api/myself
StringUtils.replace(myselfUrl, "{cloudId}", 123456);

将导致

https://url.abc/123456/api/myself