Fernando Andrade
Fernando Andrade

Reputation: 45

Regex for Replacing a subString in a String using ant

I've been struggling when trying to use regex in an ant file(using replaceregexp tag) to replace a specific string, which is not constant, in a java class, for example:
Replace: V1_0_0 by V2_0_0 In:

public void doSomething() {
    return "xxxxxxxV1_0_0.yyyyyyyy"
}

And of course V1_0_0 will always change And .yyyyyyyy will change but xxxxxxx will be the same

this is the closer I could get: (?<=xxxxxxx).* or (?<=xxxxxxx).*

but this is what I get:

public void doSomething() {
    return "xxxxxxxV2_0_0;
}

xxxxxxx or yyyyyyyy can be any characters allowed in a java class name

Upvotes: 1

Views: 212

Answers (1)

wp78de
wp78de

Reputation: 18950

Try it like this:

(?:xxxxxxx)V[0-9]+_[0-9]+_[0-9]+(?:\.[a-z]+)?

I made the yyyyyy part optional using the ?. Maybe you need a different character class than a-z, maybe [a-zA-Z] or [a-zA-Z0-9_].

Demo

Code Sample:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Ideone {
 public static void main(String[] args) throws java.lang.Exception {
  String regex = "(?:xxxxxxx)V[0-9]+_[0-9]+_[0-9]+(?:\\.[a-z]+)?";
  String string = "public void doSomething() {\n" 
                + "    return \"xxxxxxxV1_0_0.yyyyyyyy\";\n" 
                + "}";
  String subst = "xxxxxxxV2_0_0";

  Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
  Matcher matcher = pattern.matcher(string);

  String result = matcher.replaceAll(subst);
  System.out.println("Substitution result: " + result);
 }
}

Upvotes: 1

Related Questions