Pattern Matching in Java - Technical Interview 2024 - Problem Solving
Pattern Matching Logic
First thing we need to know the content we are going to do the matching and the pattern.
1. Create a reference for Pattern class and then Call the Pattern class static method compile method and send the parameter as pattern you want to search for.
2. Create reference for Matcher and assign the method which is Pattern class method matcher, here send the parameter as content we need to check.
3. Finally call the find method in Matcher class to check the pattern is matched or not. If the method is return true the pattern is matched, if the method return false the pattern is not matched.
Code :
package com.dinatechy.challange;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternMatching {
public static void main(String[] args) {
// Pattern Matching in Java
// Example : content = "Hello people hi", pattern = "hi"
// Regex
String content = "Hello people hi";
String ptn = "hi people";
Pattern pattern = Pattern.compile(ptn);
Matcher matcher = pattern.matcher(content);
if(matcher.find()) {
System.out.println("Matched");
} else {
System.out.println("No Matched");
}
}
}
Input :
hi people
Output :
No Matched
Input :
hi
Output :
Matched
For more useful programs daily follows here and subscribe to our Youtube Channel - DinaTechy....
Comments
Post a Comment