我有如下的字符串,
{Account = {type = object,id = {type = integer,format = int64},enum = [ENABLED,DISABLED]},token = {type = string}}},AssetPlayerRequest = {type = object,properties = {assetPlayer = {description =资产播放器详细信息,{$ ref =#/ definitions / AssetPlayer},ImageFile = {type = object,properties = {description = {type = string},filePath = {type = string},fileUri = {$ REF =#/定义/ URI}}}
我希望将{$ref=#/definitions/URI}
,{$ref=#/definitions/AssetPlayer}
等RegEx模式替换为地图中可用的值,例如URI
,AssetPlayer
,它们是RegEx本身的一部分。
如何在Java 8中实现这一目标?
答案 0 :(得分:1)
部分改编自Matcher.replaceAll()
:
public static void main(String[] args) {
Map<String, String> replacements = new HashMap<>();
replacements.put("AssetPlayer", "replacement1");
replacements.put("URI", "replacement2");
String input = "{Account={type=object,id={type=integer, format=int64}, enum=[ENABLED, DISABLED]}, token={type=string}}}, AssetPlayerRequest={type=object, properties={assetPlayer={description=The asset player details, {$ref=#/definitions/AssetPlayer},ImageFile={type=object, properties={description={type=string}, filePath={type=string}, fileUri={$ref=#/definitions/URI}}}";
Matcher matcher = Pattern.compile("\\{\\$ref=#\\/definitions\\/(.+?)\\}").matcher(input);
StringBuffer sb = new StringBuffer();
if (matcher.find()) {
do {
String replacement = replacements.get(matcher.group(1));
matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
} while (matcher.find());
matcher.appendTail(sb);
System.out.println(sb.toString());
} else {
System.out.println(input);
}
}
输出:
{Account={type=object,id={type=integer, format=int64}, enum=[ENABLED, DISABLED]}, token={type=string}}}, AssetPlayerRequest={type=object, properties={assetPlayer={description=The asset player details, replacement1,ImageFile={type=object, properties={description={type=string}, filePath={type=string}, fileUri=replacement2}}
答案 1 :(得分:0)
替换需要更多逻辑的字符串中的内容的通用公式位于Matcher#appendReplacement
:
public String bindTemplateVariables(String input) {
Pattern p = Pattern.compile("\\{\\$ref=#/definitions/(.*?)\\}");
Matcher m = p.matcher(input);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String replacement = map.get(m.group(1));
m.appendReplacement(sb, replacement);
}
m.appendTail(sb);
return sb.toString();
}