Java相当于PHP的preg_replace_callback [英] Java equivalent to PHP's preg_replace_callback

查看:186
本文介绍了Java相当于PHP的preg_replace_callback的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将应用程序从PHP迁移到Java,并且在代码中大量使用正则表达式。我在PHP中遇到过似乎没有java等价物的东西:

I'm in the process of moving an application from PHP to Java and there is heavy use of regular expressions in the code. I've run across something in PHP that doesn't seem to have a java equivalent:

preg_replace_callback()

对于正则表达式中的每个匹配项,它调用一个将匹配文本作为参数传递的函数。作为示例用法:

For every match in the regex, it calls a function that is passed the match text as a parameter. As an example usage:

$articleText = preg_replace_callback("/\[thumb(\d+)\]/",'thumbReplace', $articleText);
# ...
function thumbReplace($matches) {
   global $photos;
   return "<img src=\"thumbs/" . $photos[$matches[1]] . "\">";
}

在Java中执行此操作的理想方法是什么?

What would be the ideal way to do this in Java?

推荐答案

重要:正如 Kip ,如果匹配的正则表达式在替换字符串上匹配,则此类具有无限循环错误。如果有必要,我会把它留给读者来修理它。

IMPORTANT: As pointed out by Kip in the comments, this class has an infinite loop bug if the matching regex matches on the replacement string. I'll leave it as an exercise to readers to fix it, if necessary.

我什么都不知道类似于内置于Java中。使用Matcher类可以毫不费力地自己滚动:

I don't know of anything similar that's built into Java. You could roll your own without too much difficulty, using the Matcher class:

import java.util.regex.*;

public class CallbackMatcher
{
    public static interface Callback
    {
        public String foundMatch(MatchResult matchResult);
    }

    private final Pattern pattern;

    public CallbackMatcher(String regex)
    {
        this.pattern = Pattern.compile(regex);
    }

    public String replaceMatches(String string, Callback callback)
    {
        final Matcher matcher = this.pattern.matcher(string);
        while(matcher.find())
        {
            final MatchResult matchResult = matcher.toMatchResult();
            final String replacement = callback.foundMatch(matchResult);
            string = string.substring(0, matchResult.start()) +
                     replacement + string.substring(matchResult.end());
            matcher.reset(string);
        }
    }
}

然后致电:

final CallbackMatcher.Callback callback = new CallbackMatcher.Callback() {
    public String foundMatch(MatchResult matchResult)
    {
        return "<img src=\"thumbs/" + matchResults.group(1) + "\"/>";
    }
};

final CallbackMatcher callbackMatcher = new CallbackMatcher("/\[thumb(\d+)\]/");
callbackMatcher.replaceMatches(articleText, callback);

请注意,您可以通过调用 matchResults.group获取整个匹配的字符串( ) matchResults.group(0),因此没有必要将回调传递给当前字符串状态。

Note that you can get the entire matched string by calling matchResults.group() or matchResults.group(0), so it's not necessary to pass the callback the current string state.

编辑:让它看起来更像是PHP函数的确切功能。

Made it look more like the exact functionality of the PHP function.

这是原始的,因为asker喜欢它:

Here's the original, since the asker liked it:

public class CallbackMatcher
{
    public static interface Callback
    {
        public void foundMatch(MatchResult matchResult);
    }

    private final Pattern pattern;

    public CallbackMatcher(String regex)
    {
        this.pattern = Pattern.compile(regex);
    }

    public String findMatches(String string, Callback callback)
    {
        final Matcher matcher = this.pattern.matcher(string);
        while(matcher.find())
        {
            callback.foundMatch(matcher.toMatchResult());
        }
    }
}

对于这个特殊用例,最好简单地对回调中的每个匹配进行排队,然后再向后运行它们。这将防止在修改字符串时重新映射索引。

For this particular use case, it might be best to simply queue each match in the callback, then afterwards run through them backwards. This will prevent having to remap indexes as the string is modified.

这篇关于Java相当于PHP的preg_replace_callback的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆