Introduction
In this lab, you will learn how to check if a string matches a regular expression in Java. We will start by understanding the basics of regular expressions and how to create a simple pattern using the java.util.regex package.
You will then explore the Pattern and Matcher classes to perform match operations. Finally, you will apply your knowledge to test regex patterns with user input, gaining practical experience in using regular expressions for string validation and manipulation in Java.
Create a Basic Regex Pattern
In this step, we will start by understanding what regular expressions (regex) are and how to create a basic pattern in Java.
Regular expressions are powerful tools used for matching and manipulating strings of text. Think of them as a mini-language for describing patterns in text. They are incredibly useful for tasks like searching for specific text, validating input formats (like email addresses or phone numbers), and replacing text based on patterns.
In Java, regular expressions are handled by the java.util.regex package. The two main classes we'll be using are Pattern and Matcher.
Pattern: This class represents a compiled regular expression. You compile a regex string into aPatternobject.Matcher: This class is used to perform match operations against an input string by interpreting aPattern.
Let's create a simple Java program to define and print a basic regex pattern.
Open the
HelloJava.javafile in the WebIDE editor if it's not already open.Replace the entire contents of the file with the following code:
import java.util.regex.Pattern; public class HelloJava { public static void main(String[] args) { // Define a simple regex pattern to match the word "Java" String regexPattern = "Java"; // Compile the regex pattern Pattern pattern = Pattern.compile(regexPattern); // Print the pattern System.out.println("Our regex pattern is: " + pattern.pattern()); } }Let's look at the new parts:
import java.util.regex.Pattern;: This line imports thePatternclass, which we need to work with regex.String regexPattern = "Java";: This line defines a simple string variableregexPatternthat holds our regular expression. In this case, the pattern is just the literal word "Java".Pattern pattern = Pattern.compile(regexPattern);: This is where we compile our regex string into aPatternobject. ThePattern.compile()method takes the regex string as an argument and returns aPatternobject.System.out.println("Our regex pattern is: " + pattern.pattern());: This line prints the original regex string that was used to create thePatternobject. Thepattern()method of thePatternobject returns the regex string.
Save the file (Ctrl+S or Cmd+S).
Now, let's compile our program. Open the Terminal at the bottom of the WebIDE and make sure you are in the
~/projectdirectory. Run the following command:javac HelloJava.javaIf there are no errors, a
HelloJava.classfile will be created in the~/projectdirectory.Finally, run the compiled program:
java HelloJavaYou should see the following output:
Our regex pattern is: JavaThis confirms that our basic regex pattern has been successfully defined and compiled. In the next step, we will use this pattern to find matches in a given string.
Use Pattern and Matcher Classes
In this step, we will learn how to use the Matcher class with our Pattern to find occurrences of the pattern within a given input string.
As we discussed in the previous step, the Pattern class represents the compiled regular expression. The Matcher class is what we use to actually perform the search operations on a specific input string using that compiled pattern.
Here's how the process generally works:
- Compile the regex: Create a
Patternobject from your regex string usingPattern.compile(). - Create a Matcher: Get a
Matcherobject by calling thematcher()method on thePatternobject, passing the input string you want to search. - Perform the match: Use methods of the
Matcherobject to find matches. Common methods includefind()(to find the next match) andmatches()(to check if the entire input string matches the pattern).
Let's modify our HelloJava.java program to use a Matcher to find the word "Java" in a sample sentence.
Open the
HelloJava.javafile in the WebIDE editor.Replace the existing code with the following:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class HelloJava { public static void main(String[] args) { // Define a simple regex pattern to match the word "Java" String regexPattern = "Java"; // The input string to search within String inputString = "Hello, Java! Welcome to Java programming."; // Compile the regex pattern Pattern pattern = Pattern.compile(regexPattern); // Create a Matcher object Matcher matcher = pattern.matcher(inputString); // Find and print the matches System.out.println("Searching for pattern: '" + regexPattern + "' in string: '" + inputString + "'"); while (matcher.find()) { System.out.println("Found match at index: " + matcher.start()); } } }Here's what's new:
import java.util.regex.Matcher;: We import theMatcherclass.String inputString = "Hello, Java! Welcome to Java programming.";: We define the string we want to search within.Matcher matcher = pattern.matcher(inputString);: We create aMatcherobject by calling thematcher()method on ourpatternobject and passing theinputString.while (matcher.find()) { ... }: This loop uses thefind()method of theMatcher. Thefind()method attempts to find the next subsequence of the input sequence that matches the pattern. It returnstrueif a match is found, andfalseotherwise. Thewhileloop continues as long asfind()returnstrue.System.out.println("Found match at index: " + matcher.start());: Inside the loop, if a match is found,matcher.start()returns the starting index of the matched subsequence in the input string. We print this index.
Save the file (Ctrl+S or Cmd+S).
Compile the modified program in the Terminal:
javac HelloJava.javaRun the compiled program:
java HelloJavaYou should see output similar to this:
Searching for pattern: 'Java' in string: 'Hello, Java! Welcome to Java programming.' Found match at index: 7 Found match at index: 27This output shows that our program successfully found two occurrences of the word "Java" in the input string, and it printed the starting index of each match.
You have now successfully used the Pattern and Matcher classes to find a specific pattern within a string. In the next step, we will make this program interactive by allowing the user to input the string to search.
Test Regex with User Input
In this final step, we will make our regex program interactive by allowing the user to input the string they want to search within. This will make the program more flexible and demonstrate how to combine regex with user interaction.
We will use the Scanner class, which you might remember from the "Your First Java Lab", to read input from the user.
Open the
HelloJava.javafile in the WebIDE editor.Replace the existing code with the following:
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class HelloJava { public static void main(String[] args) { // Define a simple regex pattern to match the word "Java" String regexPattern = "Java"; // Create a Scanner object to read user input Scanner scanner = new Scanner(System.in); // Prompt the user to enter a string System.out.print("Enter the string to search within: "); String inputString = scanner.nextLine(); // Compile the regex pattern Pattern pattern = Pattern.compile(regexPattern); // Create a Matcher object Matcher matcher = pattern.matcher(inputString); // Find and print the matches System.out.println("Searching for pattern: '" + regexPattern + "' in string: '" + inputString + "'"); boolean found = false; while (matcher.find()) { System.out.println("Found match at index: " + matcher.start()); found = true; } if (!found) { System.out.println("No match found."); } // Close the scanner scanner.close(); } }Here are the changes we made:
import java.util.Scanner;: We import theScannerclass.Scanner scanner = new Scanner(System.in);: We create aScannerobject to read input from the console.System.out.print("Enter the string to search within: ");: We prompt the user to enter the string.String inputString = scanner.nextLine();: We read the entire line of input from the user and store it in theinputStringvariable.- We added a
boolean found = false;variable and anif (!found)block to print a message if no matches are found. scanner.close();: We close theScannerto release system resources.
Save the file (Ctrl+S or Cmd+S).
Compile the program in the Terminal:
javac HelloJava.javaRun the program:
java HelloJavaThe program will now wait for you to enter a string. Type a string that contains the word "Java" (or doesn't) and press Enter.
For example, if you enter:
Learning Java is fun!The output will be:
Enter the string to search within: Learning Java is fun! Searching for pattern: 'Java' in string: 'Learning Java is fun!' Found match at index: 9If you enter:
Python is also great.The output will be:
Enter the string to search within: Python is also great. Searching for pattern: 'Java' in string: 'Python is also great.' No match found.
You have now successfully created an interactive Java program that uses regular expressions to search for a pattern in a string provided by the user. This is a practical example of how regex can be used in real-world applications.
Summary
In this lab, we began by understanding the fundamentals of regular expressions (regex) in Java, focusing on the java.util.regex package. We learned that regex is a powerful tool for pattern matching and manipulation in strings, and that the key classes are Pattern and Matcher. We then practiced creating a basic regex pattern by defining a simple string and compiling it into a Pattern object using Pattern.compile(), demonstrating how to define and print a basic regex pattern in a Java program.



