简体   繁体   English

使用捕获的正则表达式组作为方法的参数

[英]Using captured regex group as argument to method

Normally, when using regular expressions I can refer to a captured group using the $ operator, like so: 通常,在使用正则表达式时,我可以使用$运算符引用捕获的组,如下所示:

value.replaceAll("([A-Z])", "$1"); 

What I want to know is if it is somehow possible to use the captured value in a method call, and then replace the group with the return value of the method, like so: 我想知道的是,如果在某种程度上可以在方法调用中使用捕获的值,然后使用方法的返回值替换组,如下所示:

value.replaceAll("([A-Z])", foo("$1"));

Doing it the above way does not work, unsurprisingly the passed in string is not the captured group but the string "$1" . 以上述方式执行此操作不起作用,不出所料,传入的字符串不是捕获的组,而是字符串"$1"

Is there any way I can use the captured value as an argument to some method? 有什么办法可以将捕获的值用作某种方法的参数吗? Can it be done? 可以吗?

Yes, it's possible, but you can't use the $1 construct, as you correctly point out. 是的,这是可能的,但你不能使用$1结构,正如你正确指出的那样。

Your best option is to use Pattern and Matcher for this. 您最好的选择是使用PatternMatcher

Here is an example to illustrate: 这是一个例子来说明:

import java.util.regex.*;

public class Test {

    public static String foo(String str) {
        return "<b>" + str + "</b>";
    }

    public static void main(String[] args) {
        String content = "Some Text";
        Pattern pattern = Pattern.compile("[A-Z]");
        Matcher m = pattern.matcher(content);

        StringBuffer sb = new StringBuffer();

        while (m.find())
            m.appendReplacement(sb, foo(m.group()));

        m.appendTail(sb);

        System.out.println(sb);
    }
}

Output: 输出:

<b>S</b>ome <b>T</b>ext

The replaceAll method allows $1 in the parameter string for the second argument - so your foo method would have to return a string with $1 in it, which then would be replaced. replaceAll方法允许第二个参数的参数字符串中的$1 - 所以你的foo方法必须返回一个包含$1的字符串,然后将被替换。

If you want to pass the captured group to the method, you can't use replaceAll - you have to use a Matcher with this regexp, invoke find() and then you can with .group(1) get the string corresponding to the first group, which you can then use as a replacement. 如果你想将捕获的组传递给方法,你不能使用replaceAll - 你必须使用带有这个regexp的Matcher,调用find()然后你可以用.group(1)获得对应于第一个的字符串组,您可以将其用作替代品。

Looks like aioobe was quicker than me, so I don't have to type the source code here. 看起来像aioobe比我快,所以我不必在这里输入源代码。

Usually backreferences are \\1 in PCRE regexp. 通常后向引用在PCRE正则表达式中为\\1 Maybe you can try this. 也许你可以试试这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM