Literals and Special Characters in Regular Expressions
Literals
Literals in Regular Expressions are the simplest form of patterns. They represent exact characters that must be matched in the text. For example, the literal "cat" will match the exact sequence "cat" in a string.
Example: The regular expression cat
will match:
- "The cat sat on the mat."
- "A cat is a domestic animal."
However, it will not match:
- "The dog sat on the mat."
- "A caterpillar is a type of insect."
Special Characters
Special characters in Regular Expressions have specific meanings and are used to define more complex patterns. These characters include metacharacters like .
, *
, +
, ?
, ^
, $
, \
, [
, ]
, {
, }
, (
, )
, and |
.
Common Special Characters and Their Meanings
.
(dot): Matches any single character except a newline.*
: Matches the preceding element zero or more times.+
: Matches the preceding element one or more times.?
: Matches the preceding element zero or one time.^
: Matches the start of a line.$
: Matches the end of a line.\
: Escapes a special character, making it a literal.[ ]
: Defines a character class, matching any one of the enclosed characters.{ }
: Specifies the exact number of occurrences of the preceding element.( )
: Groups elements together.|
: Acts as an OR operator, matching either the expression before or after it.
Examples of Special Characters
Example 1: The regular expression c.t
will match:
- "cat"
- "cot"
- "cut"
Example 2: The regular expression a+
will match:
- "a"
- "aa"
- "aaa"
Example 3: The regular expression colou?r
will match:
- "color"
- "colour"
Example 4: The regular expression ^start
will match:
- "start of the line"
Example 5: The regular expression end$
will match:
- "the line ends"
Example 6: The regular expression \[.*\]
will match:
- "[bracketed text]"
Example 7: The regular expression a{3}
will match:
- "aaa"
Example 8: The regular expression (cat|dog)
will match:
- "cat"
- "dog"