Nick Nick - 1 year ago 68
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?

Answer Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download