How to Convert a Java String Against a Pattern Regex?
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
// Java Program to Convert // Java String against Pattern Regex import java.util.regex.*; // Driver Class public class Temp { // Method to check pattern static void checkPattern(String testString, String regex) { // Split the string based on whitespaces String[] words = testString.split( "\\s+" ); // Compile the pattern Pattern pattern = Pattern.compile(regex); for (String word : words) { Matcher matcher = pattern.matcher(word); // Check if the string matches the pattern if (!matcher.matches()) { System.out.print(word + " " ); } } System.out.println(); } // Main Function public static void main(String[] args) { String testString = "I am in GFG. GFG is a good company and I like to work in it" ; // Define a simple regex pattern // Regex for GFG String regex = ".*\\bGFG\\b.*" ; // Call the checkPattern method checkPattern(testString, regex); } } |
Output
I am in is a good company and I like to work in it