开发者

Algorithm to search and replace delimited parameters

I have a string that contains multiple parameters delimited by #, like this :

.... #param1# ... #param2# ... #paramN# ...

And I want to replace the parameter placeholders by values开发者_高级运维.

The current algorithm looks like this:

    //retrieve place holder into this SQL select
    Pattern p = Pattern.compile(DIMConstants.FILE_LINE_ESCAPE_INDICATOR);
    Matcher m = p.matcher(sqlToExec); // get a matcher object
    int count = 0;
    int start = 0;
    int end = 0;

    StringBuilder params = new StringBuilder();
    while (m.find()) {
        count++;

        if (count % 2 == 0) {

            // Second parameter delimiter

            String patternId = sqlToExec.substring(start, m.end());

            //Clean value (#value#->value)
            String columnName = patternId.substring(1, patternId.length() - 1);

            //Look for this column into preLoad row ResultSet and retrieve its value
            String preLoadTableValue = DIMFormatUtil.convertToString(sourceRow.get(columnName));

            if (!StringUtils.isEmpty(preLoadTableValue)) {
                aSQL.append(loadGemaDao.escapeChars(preLoadTableValue).trim());
            } else {
                aSQL.append(DIMConstants.COL_VALUE_NULL);
            }
            params.append(" " + columnName + "=" + preLoadTableValue + " ");

            end = m.end();

        } else {
            // First parameter delimiter
            start = m.start();
            aSQL.append(sqlToExec.substring(end, m.start()));
        }
    }

    if (end < sqlToExec.length()) {
        aSQL.append(sqlToExec.substring(end, sqlToExec.length()));
    }

I'm looking for a simplest solution, using regexp or another public API. Input parameters will be the source string, a delimiter and a map of values. Output parameter will be the source string with all the parameters replaced.


If this is for a normal SQL query, you might want to look into using PreparedStatements

Beyond that, am I missing something? Why not just use String.replace()? Your code could look like this:

for(int i = 0; i < n; i++){
   String paramName = "#param" + i + "#"
   sqlToExec = sqlToExec.replace(paramName,values.get(paramName));
}

That assumes you have a map called "values" with string mappings between parameters in the form "#paramN#"


If you need it more generic, this will find and return the whole param including the #'s:

public class ParamFinder {

    public static void main(String[] args) {
        String foo = "#Field1# #Field2# #Field3#";

        Pattern p = Pattern.compile("#.+?#");
        Matcher m = p.matcher(foo);
        List matchesFound = new ArrayList();
        int ndx = 0;
        while(m.find(ndx)){
            matchesFound.add(m.group());
            ndx = m.end();
        }

        for(Object o : matchesFound){
            System.out.println(o);
        }


    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜