Regex or Regular Expressions are a part of the Java API. You can use the regex API to search, extract, or search and replace text strings. The regex API is available in java.util.regex package. Java uses the Pattern and Matcher classes to process regular expressions.
Here is a simple example of a Regular expression. The code searches for a pattern and prints the matching string.
/**
*
* @author Nancy K.A.N.
*/
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SimpleRegexTest {
public static void main(String[] args) {
String str1 = "This is an example of Java Regular Exressions";
Pattern pattern = Pattern.compile("Java");
Matcher matcher = pattern.matcher(str1);
if (matcher.find())
{
System.out.println(matcher.group());
}
}
}
Compile and run the code and comment the output.
Created by Nancy KAN
@13:50 13-Jun-2025