Skip to Content
bytegarden

Regular Expressions

  • Regular expressions (regex) are used for defining patterns in strings. In Java, the String class provides the matches() method to check if a string matches a given pattern

  • Syntax:

    str1.matches(regex) // Returns boolean (true/false)

Matching Symbols

Regular ExpressionDescription
.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|BA or B
XZExactly XZ

Meta Characters

  • Always use double backslashes (\\) for meta characters in Java
  • Single backslash is interpreted as Java string escape character
Regular ExpressionDescription
^Match at the beginning of a string
$Match at the end of the string
\dDigits
\DNot digits
\sSpace
\SNot Space
\wAlphabets or digits
\WNeither 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 ExpressionDescription
*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)