MySQL Regular Expressions - Regexp

been_29·2024년 7월 29일
post-thumbnail

💡 REGEXP

Powerful tools for matching patterns within text

Components of Regular Expressions

  1. Literals: The simplest type of regex. Match the exact characters you specify.

    • Example: ‘abc’ matches “abc” in the text.
  2. Metacharacters
    Define a character class. Match any single character inside the brackets.

    MarkDescription
    .Match any single character except a newline.
    ^Anchor the match at the start of a string.
    $Anchor the match at the end of a string.
    []Define a character class. Match any single character inside the brackets.
    |Alternation operator. Match either the pattern before or the pattern after the ' | '.
    ()Group patterns together.
  3. Quantifiers: Specify how many instances of a character, group, or character class must be present in the input for a match to be found.

    MarkDescription
    *Match 0 or more instances.
    +Match 1 or more instances.
    ?Match 0 or 1 instance.
    {n}Match exactly n instances.
    {n,}Match n or more instances.
    {n,m}Match between n and m instances.
  4. Character Classes

    MarkDescription
    [abc]Match any one of a, b, or c.
    [a-z]Match any lowercase letter from a to z.
    [^abc]Match any character except a, b, or c.
  5. Escape Sequences

    MarkDescription
    \.Match a literal period.
    \\Match a literal backlash.
    \dMatch any digit (equivalent to [0-9]).
    \DMatch any non-digit.
    \wMatch any word character (equivalent to [a-zA-Z0-9_]).
    \WMatch any non-word character.
    \sMatch any whitespace character (spaces, tabs, etc.).
    \SMatch any non-whitespce character.

Advanced Concepts

  1. Greedy vs. Lazy Matching
    • Greedy: a.*b matches the longest possible string starting with a and ending with b.
    • Lazy: Adding ? after a quantifier makes it lazy. a.*?b matches the shortest possible string starting with a and ending with b.
  2. Lookahead and Lookbehind Assertions: Specify a condition that must be met for a match to occur but do not consume characters in the string.
AssertionsMarkDescription
Positive Lookahead(?=…)Example: a(?=b) matches a if it is followed by b, but b is not part of the match.
Negative Lookahead(?!…)Example: a(?!b) matches a if it is not followed by b.
Positive Lookbehind(?<=…)Example: (?<=b)a matches a if it is preceded by b.
Negative Lookbehind (?<!…)Example: (?<!b)a matches a if it is not preceded by b.
profile
Data Analysis

0개의 댓글