How to Convert a Java String Against a Pattern Regex?
Last Updated :
29 Jan, 2024
Regular expressions, or “regex,” are an effective tool in Java programming for checking texts against a given pattern. This post will walk you through the process of utilizing regular expressions to validate a Java text against a pattern.
Prerequisites:
Convert Java String against Pattern Regex
Format or String structure using a regular expression pattern is used here. The Matcher class is responsible for comparing the pattern with the input string. If the full string fits the pattern, the Matcher class’s matches() function returns true.
Java
import java.util.regex.*;
public class Temp {
static void checkPattern(String testString, String regex) {
String[] words = testString.split( "\\s+" );
Pattern pattern = Pattern.compile(regex);
for (String word : words) {
Matcher matcher = pattern.matcher(word);
if (!matcher.matches()) {
System.out.print(word + " " );
}
}
System.out.println();
}
public static void main(String[] args) {
String testString = "I am in GFG. GFG is a good company and I like to work in it" ;
String regex = ".*\\bGFG\\b.*" ;
checkPattern(testString, regex);
}
}
|
Output
I am in is a good company and I like to work in it
Share your thoughts in the comments
Please Login to comment...