[英]Replace all regex matches in String with substring of match
Just wondering if there's a nicer solution to this given a String such as 只是想知道对于给定的String这样是否有更好的解决方案,例如
xDLMContent <matches> something <and> dSecurityGroup <contains> somethingelse <and> xDLMSomeOtherMetaDataField <matches> anothersomethingelse
It needs to be replaced with 它需要替换为
DLMContent <matches> something <and> SecurityGroup <contains> somethingelse <and> DLMSomeOtherMetaDataField <matches> anothersomethingelse
Rule being metadata fields begin with x or d followed by uppercase letter and then 1 or more mixed case alpha characters. 规则为元数据字段以x或d开头,后跟大写字母,然后是1个或多个大小写混合的字母字符。
Here's my solution but I'm wondering if there's something better 这是我的解决方案,但我想知道是否还有更好的选择
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);
}
Using replaceAll()
works well. 使用
replaceAll()
效果很好。 Just pick what you want to keep ( the part in brackets ()
), and replace by using $1
只需选择要保留的内容(方括号
()
的部分),然后使用$1
替换即可
String f = s.replaceAll("[dx]([A-Z][a-zA-Z]+)", "$1");
Output 输出量
DLMContent <matches> something <and> SecurityGroup <contains> somethingelse <and> DLMSomeOtherMetaDataField <matches> anothersomethingelse
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.