我会建立一个代表模式的树结构。对于您的示例,它看起来像:
root
+ variable (title)
+ group
+ text (" (by ")
+ variable (artist)
+ group
+ text (" featuring ")
+ variable (feat)
+ text (")")
然后,当您根据树评估元数据时,您会在组级别存储评估的组中的所有变量和子组,如果是,则使用文本。
您的树类看起来像:
interface Node { String evaluate(Map<String, String> metaData); }
class Group implements Node
{
private final List<Node> _children;
Group(final List<Node> children) { _children = children; }
@Override
public String evaluate(final Map<String, String> metaData)
{
final StringBuilder sb = new StringBuilder();
for (final Node node : _children)
{
final String subText = node.evaluate(metaData);
if (subText == null)
return null;
sb.append(subText);
}
return sb.toString();
}
}
class Text implements Node
{
private final String _text;
Text(final String text) { _text = text; }
@Override
public String evaluate(final Map<String, String> metaData)
{
return _text;
}
}
class Variable implements Node
{
private final String _variable;
Variable(final String variable) { _variable = variable; }
@Override
public String evaluate(final Map<String, String> metaData)
{
return metaData.get(_variable);
}
}
剩下要做的就是弄清楚如何解析字符串以创建树结构。