【问题标题】:Retrieve data from string using template使用模板从字符串中检索数据
【发布时间】:2014-11-18 21:28:21
【问题描述】:

我想根据模板中的参数从字符串中检索数据。 例如:

given string -> "some text, var=20 another part param=45"
template -> "some text, var=${var1} another part param=${var2}"
result -> var1 = 20; var2 = 45

我怎样才能在 Java 中获得这样的结果。是否有一些库或者我需要使用正则表达式? 我尝试了不同的模板处理器,但它们没有所需的功能,我需要与它们相反的东西。

【问题讨论】:

  • 是的,使用正则表达式。

标签: java string templates


【解决方案1】:

我希望下面的示例能满足您的目的 -

    String strValue = "some text, var=20 another part param=45";
    String strTemplate = "some text, var=${var1} another part param=${var2}";
    ArrayList<String> wildcards = new ArrayList<String>();
    StringBuffer outputBuffer = new StringBuffer();

    Pattern pat1 = Pattern.compile("(\\$\\{\\w*\\})");
    Matcher mat1 = pat1.matcher(strTemplate);

    while (mat1.find()) 
    {
        wildcards.add(mat1.group(1).replaceAll("\\$", "").replaceAll("\\{", "").replaceAll("\\}", ""));
        strTemplate = strTemplate.replace(mat1.group(1), "(\\w*)");
    }

    if(wildcards!= null && wildcards.size() > 0)
    {
        Pattern pat2 = Pattern.compile(strTemplate);
        Matcher mat2 = pat2.matcher(strValue);

        if (mat2.find()) 
        {
            for(int i=0;i<wildcards.size();i++)
            {
                outputBuffer.append(wildcards.get(i)).append(" = ");
                outputBuffer.append(mat2.group(i+1));
                if(i != wildcards.size()-1)
                {
                    outputBuffer.append("; ");
                }
            }
        }
    }

    System.out.println(outputBuffer.toString());

【讨论】:

    猜你喜欢
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2010-10-16
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多