只是想知道在给定字符串(例如
)的情况下是否有更好的解决方案xDLMContent <matches> something <and> dSecurityGroup <contains> somethingelse <and> xDLMSomeOtherMetaDataField <matches> anothersomethingelse
需要替换为
DLMContent <matches> something <and> SecurityGroup <contains> somethingelse <and> DLMSomeOtherMetaDataField <matches> anothersomethingelse
作为元数据字段的规则以x或d开头,后跟大写字母,然后是1个或多个混合大小写字母字符。
这是我的解决方案,但我想知道是否有更好的东西
public static void main(String[] args) {
String s = "xDLMContent <matches> something <and> dSecurityGroup <contains> somethingelse <and> xDLMSomeOtherMetaDataField <matches> anothersomethingelse";
Pattern pattern = Pattern.compile("[dx][A-Z][a-zA-Z]+");
Matcher matcher = pattern.match(s);
while (matcher.find()) {
String orig = s.substring(matcher.start(), matcher.end());
String rep = s.substring(matcher.start() + 1, matcher.end());
s = s.replaceAll(orig, rep);
matcher = pattern.match(s);
}
System.out.println(s);
}
答案 0 :(得分:4)
使用replaceAll()
效果很好。只需选择要保留的内容(括号()
中的部分),然后使用$1
替换
String f = s.replaceAll("[dx]([A-Z][a-zA-Z]+)", "$1");
输出
DLMContent <matches> something <and> SecurityGroup <contains> somethingelse <and> DLMSomeOtherMetaDataField <matches> anothersomethingelse