我们知道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
我想现在你可能理解我的意思了。是否有一个成熟的图书馆来完成这种复杂的“反正则表达”工作?
答案 0 :(得分: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" );
会给: “选择名字,来自人的名字”
我将把剩下的实现(以及健壮性等)留给你......