Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using functions or methods in Java's String.replaceAll() regex

Tags:

java

string

regex

I am trying to convert an RPN-equation into a string that matches tigcc rules. There numbers must have the number of chars in front of them and a tag for positive or negative. For "2" it would be "1 2 POSINT_TAG"

My complete input to rpn converter is based on regexes, so I wanted to use them again and have a String.replaceAll() function like:

string.replaceAll("(\d+)","$1".length+" $1 POSINT_TAG");

But there it just prints: "2 number INT_TAG". I found some classes like com.stevesoft.pat (link).

Is there another way implemented in normal Sun Java to use (custom) functions in replace rules of regexes?

like image 320
Nick Avatar asked Jan 20 '11 00:01

Nick


1 Answers

No, at least not the same way you would do it in C# or Ruby.

The closest thing is to write a loop like this:

static Pattern pattern = Pattern.compile("\\d+");
String convert(String input) {
    StringBuffer output = new StringBuffer();
    Matcher matcher = pattern.matcher(input);
    while (matcher.find()) {
        String rep =
            String.format("%d %s POSINT_TAG",
                          matcher.group().length(),
                          matcher.group());
        matcher.appendReplacement(output, rep);
    }
    matcher.appendTail(output);
    return output.toString();
}
like image 70
finnw Avatar answered Nov 15 '22 05:11

finnw