What is Java Regular Expressions?
From Oracle, it says “Regular expressions are a way to describe a set of strings based on common characteristics shared by each string in the set.” In order to define that common characteristics, we prepare a sequence of characters called ‘Pattern’. These patterns can be used to search, edit, or manipulate text and data.
java.util.regex
API
The regular expression syntax in the java.util.regex
API which consists of three classes: Pattern, Matcher, and PatternSyntaxException.
Pattern
- A
Pattern
object is a compiled representation of a regular expression. - The
Pattern
class provides no public constructors. - To create a pattern, you must first invoke one of its public static
compile()
methods, which will then return aPattern
object. - These methods accept a regular expression as the first argument; the following sections are covering the required syntax.
Matcher
- A
Matcher
object is the engine that interprets the pattern and performs match operations against an input string. - Like the
Pattern
class,Matcher
defines no public constructors. - You obtain a
Matcher
object by invoking thematcher()
method on aPattern
object
PatternSyntaxException
- A
PatternSyntaxException
object is an unchecked exception that indicates a syntax error in a regular expression pattern.
Demo
package com.bruiser.regexp;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExp {
public static void main(String[] args) {
String searchPattern = "Tech";
String inputString = "Welcome To TechBruiser!";
Pattern pattern = Pattern.compile(searchPattern);
Matcher matcher = pattern.matcher(inputString);
boolean matchFound = matcher.find();
if(matchFound) {
System.out.printf("The search pattern '%s' is available in input '%s' ", searchPattern, inputString);
}else {
System.out.printf("Match no found");
}
}
}
The search pattern 'Tech' is available in input 'Welcome To TechBruiser!'
Great. Now we know about java regular expressions. But is that all about regular expressions ? No way. it is just a kickstart. Let’s move on to the next session to get most out of regular expression.