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

查看:32
本文介绍了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.

这是原文,因为提问者喜欢它:

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天全站免登陆