Java RegEx Methods
Pattern Methods
A regular expression (regex) is a pattern that describes text, for example "one or more digits". You can use it to search, check and replace text.
The Pattern class holds a regular expression. Create a pattern with Pattern.compile(), and then use its matcher() method to get a Matcher. Both classes are in the java.util.regex package, so you must import them first.
| Method | Description | Return Type |
|---|---|---|
| compile() | Turns a regular expression into a Pattern object | Pattern |
| flags() | Returns the flags (options) that the pattern was created with | int |
| matcher() | Creates a Matcher object that can search a text for the pattern | Matcher |
| matches() | Checks if a whole text matches a regular expression, without creating a Pattern first | boolean |
| pattern() | Returns the regular expression that the pattern was created from | String |
| quote() | Returns a regular expression that matches the text exactly, with no special characters | String |
| split() | Splits a text into an array of parts, at each match of the pattern | String[] |
Matcher Methods
A Matcher object searches a text for a pattern. Its methods find the matches, tell you where they are, and replace them.
| Method | Description | Return Type |
|---|---|---|
| end() | Returns the index after the last character of the match | int |
| find() | Searches the text for the next match of the pattern | boolean |
| group() | Returns the text that was found by the last match, or by a group in it | String |
| groupCount() | Returns the number of groups in the pattern | int |
| lookingAt() | Checks if the beginning of the text matches the pattern | boolean |
| matches() | Checks if the whole text matches the pattern | boolean |
| replaceAll() | Replaces every match of the pattern with a new text | String |
| replaceFirst() | Replaces the first match of the pattern with a new text | String |
| reset() | Resets the matcher, so the next search starts from the beginning of the text | Matcher |
| start() | Returns the index of the first character of the match | int |