Regular Expressions
-
Regular expressions (regex) are used for defining patterns in strings. In Java, the
Stringclass provides thematches()method to check if a string matches a given pattern -
Syntax:
str1.matches(regex) // Returns boolean (true/false)
Matching Symbols
| Regular Expression | Description |
|---|---|
. | Any Character |
[abc] | Exactly one of a, b, or c |
[abc][vz] | Either a, b, or c followed by either v or z |
[a-z][0-9] | a to z followed by 0 to 9 |
[^abc] | Except a, b, or c |
[a-z1-7] | a to z or 1 to 7 |
A|B | A or B |
XZ | Exactly XZ |
Meta Characters
- Always use double backslashes (
\\) for meta characters in Java - Single backslash is interpreted as Java string escape character
| Regular Expression | Description |
|---|---|
^ | Match at the beginning of a string |
$ | Match at the end of the string |
\d | Digits |
\D | Not digits |
\s | Space |
\S | Not Space |
\w | Alphabets or digits |
\W | Neither alphabet not digit (special characters) |
Quantifiers
- Quantifiers specify how many times a symbol or pattern can occur in a string
- Extend pattern matching from single characters to multiple characters
| Regular Expression | Description |
|---|---|
* | 0 or more times (matches any number of occurrences) |
+ | 1 or more times (must appear at least once) |
? | 0 or 1 time (makes the element optional) |
{X} | Exactly X times |
{X, Y} | Between X & Y times (inclusive) |
{X,} | At least X times (X or more) |