0

我们知道 String.format() 可以接受这种风格的格式: %[argument_index$][flags][width][.precision]conversion 这就是众所周知的 C printf() 格式,并在 java 1.5 中引入。

我的任务是生成复杂的格式,包括重复或可选参数。例如,使用以下格式:

select %1 from %2 where %3 and give %1->'*' %2->'users' %3->'age>20' 

它返回:

select * from users where age>20

Stirng.format() 可以支持该格式。

但是,我希望格式类似于:

select %1{, } from (%2(as %3)){,} (where %4 (and %5))?
when: %1->'*', %2->'users' %3->null, %3->'age>20' 

它返回:

select * from users where age>20
when: %1->Stirng{'name','age'} , %2->'users' %3->'u', %4->'age>20', %5->null 

它返回:

select name, age from users as u where age>20
when: %1->Stirng{'name','age'} , %2->'users' %3->'u', %4->null, %5->null 

它返回:

select name, age from users as u
when: %1->Stirng{'name','age'} , %2->String{'users','order'} %3->{'u','o'}, %4->'age>20',    %5->'u.id=o.userid' 

它返回:

select name, age from users as u,orders as o where age>20 and u.id=o.userid

我想现在你可能明白我的意思了。是否有成熟的库来完成如此复杂的“反正则表达式”工作?

4

1 回答 1

1

也许您正在寻找 CustomFormatProvider?

class SqlFormatter:IFormatProvider, ICustomFormatter
    {

        public object GetFormat(Type formatType)
        {
            return this;
        }


        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            StringBuilder concat = new StringBuilder();

            string[] formatParts = format.Split(':');

            switch (formatParts[0])
            {
                case "sqlfield":
                    string sep = "";
                    if (formatParts.Length>1)
                    {
                        sep = formatParts[1];
                    }
                    string[] fields = (string[]) arg;
                    concat.Append(fields[0]);
                    for (int fieldIndex = 1; fieldIndex < fields.Length; fieldIndex++)
                    {
                        concat.Append(sep);
                        concat.Append(fields[fieldIndex]);
                    }
                    break;
                case "sqltables":
                    concat.Append(arg.ToString());
                    break;
                default:
                    break;
            }
            return concat.ToString(); 
        }
    }

像这样使用它:

 String sql = String.Format(
           new SqlFormatter()
           , "select {0:sqlfield:,} from {1:sqltables} "
           , new string[]{"name","lname"}
           , "person" );

将给出:“select name,lname from person”

我将把其余的实现(和健壮性等)留给你......

于 2011-02-26T17:41:42.237 回答