Question

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.

Was it helpful?

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());
    }
}
}

OTHER TIPS

You should use String's methods replaceFirst(..) or replaceAll(..):

String s1 = "fb";
String r1 = s1.replaceFirst("(f(\\w+))", "$1=$2");
System.out.println(r1);
// fb=b

String s2 = "Rab";
String r2 = s2.replaceFirst("(R)(\\w+)(\\w+)", "$1$3$2");
System.out.println(r2);
// Rba

String s3 = "Fa&Ga";
String r3 = s3.replaceFirst("F(\\w+)&G\\1", "$1");
System.out.println(r3);
// a
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top