A regular expression is a defined pattern used for matching and manipulating strings. In Java, there is a built-in API for regular expressions:
java.util.regex package
This package has three classes:
This regular expression is not the property of one particular programming language; instead, it is supported by multiple languages.
The util.regex.Matcher
is used for match operations using the text patterns.
Some of the most commonly used methods are:
Methods | Description |
---|---|
find() |
It searches the occurrences of an expression in a text. |
find(int index) |
It searches the occurrences of an expression in a text from the given index. |
start() |
It returns the starting index of the match that is found. |
end() |
It returns the ending index of the match that is found. |
groupCount() |
It returns an integer value for the total number of matched values. |
// Java programimport java.util.regex.Matcher;import java.util.regex.Pattern;class Main{public static void main(String [] arguments){// Create a pattern to be searchedPattern pttrn = Pattern.compile("Ah*");// Search the pattern in the given textMatcher mtch = pttrn.matcher("Ahhhhh! I lost my job.");// search and print the starting and ending index using// end() and start() function.while (mtch.find())System.out.println("Starting index: " + mtch.start() +" Ending index: " + (mtch.end()-1));}}
In the above code, some of the functions from the pattern class are used. These are detailed here.
The “*” symbol in the above code means that the character before it can repeat finitely at that position (e.g., hel*o is equivalent to hello).