Search code examples
javaregexstringextend

Complete String so that it matches regex


I have a string and a regex like the following:

fb
f(\w+)=\1

I would like to use these to generate:

fb=b

Is there any way to do this in Java? I can confirm that fb matches the f(\w+) using .matches(), but I can't figure out how to extend the string to match the full regex. I've found Xeger in searching, but this seems to generate random matching strings.

A possibility I see is to use Xeger to generate potential strings of the form

f(\w+)=\1

and then check if the first two characters of the result are fb, but is there less cumbersome way?

I have a number of strings of a similar format to this, where there is a quantified binary operation and a match for the first argument. I need to generate the appropriate second argument. Further examples:

Rab
R(\w+)(\w+)=R\2\1

to generate Rba.

Fa&Ga
(F(\w+)=G\1) implies \1

to generate a.


Solution

  • You can use the java.util.regex.Pattern and java.util.regex.Matcher to solve your problem.I am posting a code snippet whose output will be any string starting with 'f' and any number of character following it.

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    class Test
    {
    public static void main(final String[] args)
    {
        final Pattern pattern = Pattern.compile("f(\\w+)");
        final Matcher matcher = pattern.matcher("fb=1");
        while (matcher.find())
        {
            System.out.println(matcher.group());
        }
    }
    }