开发者

Using captured regex group as argument to method

Normally, when using regular expressio开发者_C百科ns 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".

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.

Your best option is to use Pattern and Matcher for this.

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.

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.

Looks like aioobe was quicker than me, so I don't have to type the source code here.


Usually backreferences are \1 in PCRE regexp. Maybe you can try this.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜