1

Just wondering if there's a nicer solution to this given a String such as

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.

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);
}
PDStat
  • 5,513
  • 10
  • 51
  • 86

1 Answers1

8

Using replaceAll() works well. Just pick what you want to keep ( the part in brackets () ), and replace by using $1

String f = s.replaceAll("[dx]([A-Z][a-zA-Z]+)", "$1");

Output

DLMContent <matches> something <and> SecurityGroup <contains> somethingelse <and> DLMSomeOtherMetaDataField <matches> anothersomethingelse
baao
  • 71,625
  • 17
  • 143
  • 203
  • 2
    Do you know whether there is a possibility to perform some transformation on this group, like so: `replaceAll("[dx]([A-Z][a-zA-Z]+)", someMethod("$1"))` ? (obviously, this code does not work - maybe there is some other trick to this) – Alex Semeniuk Nov 23 '17 at 09:24