ramp
ramp

Reputation: 1256

Regex back reference to match a number (or any char sequence) with itself

I am missing something basic here. I have this regex (.*)=\1 and I am using it to match 100=100 and its failing. When I remove the back reference from the regex and continue to use the capturing group, it shows that the captured group is '100'. Why does it not work when I try to use the back reference?

package test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexTest {

    public static void main(String[] args) {
        String eqPattern = "(.*)=\1";
        String input[] = {"1=1"};
        testAndPrint(eqPattern, input); // this does not work

        eqPattern = "(.*)=";
        input = new String[]{"1=1"};
        testAndPrint(eqPattern, input); // this works when the backreference is removed from the expr
    }

    static void testAndPrint(String regexPattern, String[] input) {
        System.out.println("\n Regex pattern is "+regexPattern);
        Pattern p = Pattern.compile(regexPattern, Pattern.CASE_INSENSITIVE);
        boolean found = false;
        for (String str : input) {
            System.out.println("Testing "+str);
            Matcher matcher = p.matcher(str);
            while (matcher.find()) {
                System.out.println("I found the text "+ matcher.group() +" starting at " + "index "+ matcher.start()+" and ending at index "+matcher.end());
                found = true;
                System.out.println("Group captured "+matcher.group(1)); 
            }

            if (!found) {
                System.out.println("No match found");
            }
        }
    }
}

When I run this, I get the following output

Regex pattern is (.*)=\1
Testing 100=100
No match found

 Regex pattern is (.*)=
Testing 100=100
I found the text 100= starting at index 0 and ending at index 4
Group captured 100 -->If the group contains 100, why doesnt it match when I add \1 above

?

Upvotes: 0

Views: 70

Answers (2)

Shiping
Shiping

Reputation: 1327

I think you need to escape the backslash.

String eqPattern = "(.*)=\\1";

Upvotes: 0

Raman Sahasi
Raman Sahasi

Reputation: 31851

You have to escape the pattern string.

String eqPattern = "(.*)=\\1";

Upvotes: 3

Related Questions