简体   繁体   中英

Retrieve data from string using template

I'd like to retrieve data from string based on params from template. For example:

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

How could I achive that result in Java. Are there some libs or I need to use regex? I tried different template processors, but they don't have needed functionality, I need something like inverse to them.

I hope below sample will serve your purpose -

    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());

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