开发者

how to do regular expression replacer function in java?

开发者 https://www.devze.com 2023-02-15 17:31 出处:网络
In python , I can use a replacer function in sub(), that is very powerful for some situation, like this:

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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消