zhongshu
zhongshu

Reputation: 7878

how to do regular expression replacer function in java?

In python , I can use a replacer function in sub(), that is very powerful for some situation, like this:

def replacer(match):
    s = match.group(0)
    if s.startswith('/'):
        return ""
    else:
        return s
return re.sub(pattern, replacer, text)

how to do this in Java?

Upvotes: 2

Views: 141

Answers (2)

Stephen C
Stephen C

Reputation: 719238

You cannot do that in Java.

The replace* methods in the Matcher class take a String argument to specify the replacement. What you are trying to do would require a replace method with a different signature.

You can't even hack a solution by creating a subclass of Matcher: it is a final class.

Upvotes: 1

Jeanne Boyarsky
Jeanne Boyarsky

Reputation: 12266

In Java, there is an idiom:

Pattern pattern = Pattern.compile(yourPattern);
Matcher matcher = patern.matcher(yourString);
while (matcher.find()) {
  String group = matcher.group(0);
  // do your if statement
}

One tip that's not readily apparent from the documentation - if yourString has special (reg exp) characters in it, it is important to use matcher.appendReplacement(stringBuffer) and matcher.appendTail(stringBuffer) to avoid errors.

Upvotes: 4

Related Questions