Preventing Matches with Character Classes

Previous examples used character classes to specify exact sequences to match. Character classes can also be used to prevent, or negate, matches with undesirable strings. To prevent a match, use a leading caret "^" (meaning NOT), within square brackets, [^...]. For example, the regex [^a] matches any single character except the letter "a".

Note: The caret symbol must be the first character within the square brackets to negate a character class.

Using character classes to prevent a sequence from matching.

Example 1: Prevent a match on any numeric string. Use the "*" to match an item 0 or more times.

  • Regex:
    [^0-9]*
  • Matches:
    abc
    c
    Mail
    u-see
    a4a
  • Doesn't Match:
    1
    42
    100
    23000000

Example 2: Search for a text file beginning with any character not a lower-case letter.

  • Regex:
    [^a-z]\.txt
  • Matches:
    A.txt
    4.txt
    Z.txt
  • Doesn't Match:
    r.txt
    a.txt
    Aa.txt

Example 3: Prevent a match on the numbers "10" and "12".

  • Regex:
    1[^02]
  • Matches:
    13
    11
    19
    17
    1a
  • Doesn't Match:
    10
    12
    42
    a1