Question

I am not sure if this is possible to do, but I need a way to replace a value of a numbered group specified in the my regex expression with a string declared dynamically at runtime, once a match has been made.

Given a simple case, something like...

(/)?([A-Za-z0-9])?(/)?$

I would want to be able to plugin a replacement for group 2.

I am currently using Java's Matcher class.

Was it helpful?

Solution

Yes, that's doable. Check out my answer to this question to see how. In fact, this question probably should be closed as a duplicate.

You'll need to change the regex a little. I can't tell exactly what you're trying to do, so I can't give any specifics, but at the very least you should move all those question marks inside the groups.

(/)?([A-Za-z0-9])?(/)?$  // NO

(/?)([A-Za-z0-9]?)(/?)$  // YES

But it will still match an empty substring at the end of the target string, because everything is optional except the anchor, $. Is that really what you meant to do?

OTHER TIPS

I am not sure if this is possible to do...

Yes, it's possible. See the example below.

I would want to be able to plugin a replacement for group 2.

This demo "plugs in" the .toUpperCase version of group 2 as a replacement.

import java.util.regex.*;

class Main {
    public static void main(String... args) {
        String input = "hello my name is /aioobe/ and I like /patterns/.";
        Pattern p = Pattern.compile("(/)([A-Za-z0-9]+)(/)");
        Matcher m = p.matcher(input);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            String rep = m.group(1) + m.group(2).toUpperCase() + m.group(3);
            m.appendReplacement(sb, rep);
        }
        m.appendTail(sb);
        System.out.println(sb);
    }
}

Prints:

hello my name is /AIOOBE/ and I like /PATTERNS/.

Return the value of your regex search and save it to a variable, then do a replace on your main string using your regex search results as a find target and your dynamically declared string as a replacement.

Really simplified conceptual:

String testString = "Hello there";
//String substring = *Do your regex work here*
if(substring.length() > 0) {
   testString.replace(substring, dynamicallyGeneratedString); 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top