ADVERTISEMENT
ADVERTISEMENT

Java program to count the occurrence of pattern matching in the string using regular expression

Given a string, we have to count the occurrence of pattern matching using regular expression.
Submitted by Nidhi, on June 12, 2022

Problem Solution:

In this program, we will create a string and a regular expression pattern. Then we will count the occurrence of pattern matching in the string using the find() method.

Program/Source Code:

The source code to count the occurrence of pattern matching in the string using regular expression is given below. The given program is compiled and executed successfully.

// Java program to count the occurrence of pattern matching 
// in the string using regular expression

import java.util.regex.*;

public class Main {
  public static void main(String[] args) {
    String str = "bcd abc xyz abc pqr lmn";
    String regex = "abc";

    int count = 0;

    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(str);

    while (matcher.find()) {
      count++;
    }

    System.out.println("Pattern matching count: " + count);
  }
}

Output:

Pattern matching count: 2

Explanation:

In the above program, we imported the "java.util.regex.*" package to use the Pattern and Matcher classes. Here, we created a public class Main.

The Main class contains a main() method. The main() method is the entry point for the program. And, created a string and pattern. Then we used the find() method to count the occurrence of pattern matching in the string using regular expression and printed the result.

Java Regular Expressions Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.