javaregexjava.util.scanner

I am passing variables in Pattern.compile() and .matcher() but not getting required output


I wrote a program that asks the user for a target String and a pattern to be searched in it. It is intended to find the position of the matched pattern and how many times it is present in the target string. But it always shows no pattern was found even if the pattern is present in the target string. I have written a function searchPattern() for it.

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

    public class Main
    {
        private static Scanner sc = new Scanner(System.in);
        public static void main(String[] args)
        {

            String pattern,target;
            System.out.println("Enter Target String: ");
            pattern = sc.nextLine();
            System.out.println("Enter pattern to be searched: ");
            target = sc.nextLine();
            searchPattern(pattern,target);
        }
        public static void searchPattern(String pattern,String target)
        {
            Pattern p = Pattern.compile(pattern);
            Matcher m = p.matcher(target);
            int count = 0;
            //if(!m.find())return;
            while (m.find())
            {
                count ++;
                System.out.println(m.start() + "--" + m.end() + "--" + m.group());
            }
            if (count == 0)
                System.out.println("Your pattern was not found in the target string");
            else
                System.out.println("Total occurrences of 'ab' are" + count);

        }
    }

It gives the following output:

Enter Target String: 
ababbab
Enter pattern to be searched: 
ab
Your pattern was not found in the target string

Even if 'ab' is present in the target String, why isn't this code working


Solution

  • You're storing the target and pattern in the wrong variables

    private static Scanner sc = new Scanner(System.in);
    
    public static void main(String[] args) {
    
        String pattern, target;
        System.out.println("Enter Target String: ");
        target = sc.nextLine();
        System.out.println("Enter pattern to be searched: ");
        pattern = sc.nextLine();
        searchPattern(pattern, target);
    }
    
    public static void searchPattern(String pattern, String target) {
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(target);
        int count = 0;
        while (m.find()) {
            count++;
            System.out.println(m.start() + "--" + m.end() + "--" + m.group());
        }
        if (count == 0) {
            System.out.println("Your pattern was not found in the target string");
        } else {
            System.out.println("Total occurrences of " + pattern + " are" + count);
        }
    }