Negative Lookahead

  • + 0 comments

    Java 15

    import java.io.*;
    import java.util.*;
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    public class Solution {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            Pattern pattern = Pattern.compile("(.)(?!\\1)"); 
            // "\\1" is a backreference to the first captured group. It is a backreference which will be translated into the same character found in (.), whatever character that is.
            // Note: Does not work without parenthesis: ".(?!\\1)"
            Matcher matcher = pattern.matcher(scanner.next());
            int count=0;
            while(matcher.find()) count++;
            System.out.println("Number of matches : "+count);
        }
    }