Nick Nick - 6 months ago 24
Java Question

Using functions or methods in Java's String.replaceAll() 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

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?


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.appendReplacement(output, rep);
    return output.toString();