从字符串中提取占位符

时间:2018-08-09 15:34:15

标签: java string replace split

我有2个字符串。一个包含“格式”和占位符,而另一个包含占位符的实际值。

例如:

字符串一:"<username> <password>"

字符串二:"myUser myPass"

字符串一:"<name>, <familyName>"

字符串二:"John, Smith"

我正在尝试在第二个字符串中为变量String username分配用户名占位符的值,并在第二个字符串中为变量String password分配密码占位符的值。

我知道String.replaceAll()方法,但是那不就是将第二个字符串替换为第一个字符串吗?

3 个答案:

答案 0 :(得分:3)

一种可行的解决方法是维护令牌及其替换图。然后,您可以迭代该地图并将替换内容应用于文本,如下所示:

String text = "There is a user <username> who has a password <password>";
Map<String, String> tokens = new HashMap<>();
tokens.put("<username>", "myUser");
tokens.put("<password>", "myPass");

for (Map.Entry<String, String> entry : tokens.entrySet()) {
    text = text.replaceAll(entry.getKey(), entry.getValue());
}

System.out.println(text);

There is a user myUser who has a password myPass

Demo

答案 1 :(得分:1)

这解决了普通的String::replaceAll方法:

String one ="<username> <password>";
String two = "<name>, <familyName>";

String username = "myUser";
String password = "myPass";
String name = "John";
String familyName = "Smith";

// will result in "myUser myPass" without the quotation marks
String outputOne = one.replaceAll("<username>", username).replaceAll("<password>", password);

// will result in "John Smith" without the quotation marks
String outputTwo = two.replaceAll("<name>", name).replaceAll("<familyName>", familyName);

答案 2 :(得分:0)

我建议继续使用正则表达式。首先从字符串1捕获所有键,然后创建相应的正则表达式,并从中获取字符串2的值。

提取键和相应值的代码:

    String keyString = "<name>, <familyName>";
    int i  = 0;
    List<String> keys = new ArrayList<>();
    Pattern pattern = Pattern.compile("<(\\w+)>");
    Matcher matcher = pattern.matcher(keyString);
    StringBuilder sb = new StringBuilder("");
    while(matcher.find()) {
            String token = matcher.group(1);
        sb.append(keyString.substring(i, matcher.start()));
        sb.append("([\\w ]+)");
        keys.add(token);
        i = matcher.end();
    }

    Pattern valuePattern = Pattern.compile(sb.toString());
    Matcher valueMatcher = valuePattern.matcher("John, Smith");
    Map<String,String> keyValueMap = new HashMap<>();
    while(valueMatcher.find()) {
        int counter = 0;
        for(String key:keys) {
            keyValueMap.put(key, valueMatcher.group(++counter));
    }
}

Similary对所有其他键值对执行。

最终JShell输出:

jshell> keyValueMap
keyValueMap ==> {password=myPass, familyName=Smith, name=John, username=myUser}