Regex backreferences in Java

前端 未结 2 625
你的背包
你的背包 2021-01-03 04:26

I had to match a number followed by itself 14 times. Then I\'ve came to the following regular expression in the regexstor.net/tester:

(\\d)\\1{14}
         


        
2条回答
  •  悲&欢浪女
    2021-01-03 04:52

    I think the main Problem is not the backreference - which works perfectly fine with \1 in java.

    Your Problem is more likely the "overall" escaping of a regex pattern in Java.

    If you want to have the pattern

    (\d)\1{14}
    

    passed to the regex engine, you first need to escape it cause it's a java-string when you write it:

    (\\d)\\1{14}
    

    Voila, works like a charm: goo.gl/BNCx7B (add http://, SO does not allow Url-Shorteners, but tutorialspoint.com has no other option as it seems)

    Offline-Example:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class HelloWorld{
    
         public static void main(String []args){
            String test = "555555555555555"; // 5 followed by 5 for 14 times.
    
            String pattern = "(\\d)\\1{14}";
    
            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(test);
            if (m.find( )) {
               System.out.println("Matched!");   
            }else{
               System.out.println("not matched :-(");    
            }
         }
    }
    

提交回复
热议问题