Basic Syntax

Regular expressions are powerful text matching tools used to find, replace, or validate specific patterns in strings.

What are Regular Expressions?

Regular expressions are patterns composed of ordinary characters and special characters, used to describe matching rules for strings.

Simple Examples:
hello - matches the string "hello"
\d - matches any digit
[a-z] - matches any lowercase letter

Basic Components

  • Ordinary Characters: directly match the character itself
  • Metacharacters: characters with special meanings
  • Quantifiers: specify the number of matches
  • Character Classes: match any one character from a group

Metacharacters

Metacharacters are special characters that have specific meanings in regular expressions.

Common Metacharacters:
. - matches any character except newline
^ - matches the start of a string
$ - matches the end of a string
* - matches 0 or more of the preceding element
+ - matches 1 or more of the preceding element
? - matches 0 or 1 of the preceding element

Quantifiers

Quantifiers specify how many times a character or group should be matched.

Common Quantifiers:
{n} - matches exactly n times
{n,} - matches n or more times
{n,m} - matches between n and m times

Character Classes

Character classes allow you to match any one character from a set of characters.

Common Character Classes:
[abc] - matches a, b, or c
[a-z] - matches any lowercase letter
[0-9] - matches any digit
[^abc] - matches any character except a, b, or c

Groups

Groups allow you to apply quantifiers to multiple characters and capture matched text.

Group Examples:
(abc) - matches "abc" as a group
(abc)+ - matches one or more "abc" groups
(a|b) - matches either "a" or "b"

Anchors

Anchors specify the position in the string where a match should occur.

Common Anchors:
^ - start of string
$ - end of string
\b - word boundary
\B - non-word boundary

Flags

Flags modify how the regular expression is interpreted.

Common Flags:
g - global match (find all matches)
i - case insensitive
m - multiline mode
s - dot matches newline

Advanced Techniques

Advanced regular expression techniques for complex pattern matching.

Advanced Patterns:
(?=pattern) - positive lookahead
(?!pattern) - negative lookahead
(?<=pattern) - positive lookbehind
(? - negative lookbehind

Practice Exercises

Test your knowledge with these practical exercises.

Exercise 1: Email Validation

Create a regex to validate email addresses.

^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$

Exercise 2: Phone Number

Create a regex to match phone numbers.

^1[3-9]\d{9}$

Exercise 3: Date Format

Create a regex to match YYYY-MM-DD date format.

^\d{4}-\d{2}-\d{2}$