Special Character Classes Explained with Examples

UpComing SoftWare Training Demos

πŸš€ *Gen AI EngineerΒ Telugu (Production Focused)*
πŸ—“οΈ *Date:* 30th Sept 2026, 07:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/gr
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/gw
πŸ’‘*Course Content:*
https://www.vlrt.in/ai
▢️ *Demo Videos:*
https://www.vlrt.in/gv

πŸš€ *Service now Admin/ Development (ITSM)FREE Demo in Telugu*
πŸ—“οΈ *Date:* 30th Sept 2026, 08:00AM IST
πŸ“ *Register Now!:*
https://www.vlrt.in/7r
πŸ‘₯ *Join WA Community:*
https://www.vlrt.in/7w
πŸ’‘*Course Content:*
https://www.vlrt.in/7c
▢️ *Demo Videos:*
https://www.vlrt.in/7v

πŸš€ *Vulnerability Management Training Demo*
πŸ—“οΈ *Date:* 30th Sept 2026, 09:00 AM IST
πŸ“*Register Now!:*
https://www.vlrt.in/vr
πŸ‘₯ *Join Community:*
https://www.vlrt.in/cw
πŸ’‘ *Course Content:*
https://www.vlrt.in/vc
▢️ *Demo Videos:*
https://www.vlrt.in/Vm

Special Character Classes Explained with Examples

1. [\\\^\-\]] – Escaped special characters in brackets

Description: Matches literal backslash, caret, hyphen, or closing bracket characters inside character classes

Example 1: Matching literal special characters

python

import re

text = "Special chars: \\ ^ - ] ["
result = re.findall(r'[\\\^\-\]]', text)
print(result)  # ['\\', '^', '-', ']']
# Matches literal \, ^, -, and ] characters

Example 2: Extracting file paths with backslashes

python

text = "Paths: C:\\Windows\\System32, /usr/bin/, D:\\Program Files\\"
result = re.findall(r'[A-Z]:[\\\w]+', text)
print(result)  # ['C:\\Windows', 'D:\\Program']
# Matches Windows paths with literal backslashes

Example 3: Finding mathematical ranges

python

text = "Ranges: 1-10, 20-30, A-Z, 5-10, a-z"
result = re.findall(r'[A-Za-z0-9]\-[A-Za-z0-9]', text)
print(result)  # ['1-1', '0-3', 'A-Z', '5-1', 'a-z']
# Matches range patterns with literal hyphens

Example 4: Escaping regex metacharacters in search

python

text = "Regex specials: [group], ^start, end$, .any, *star"
result = re.findall(r'[\^\.\*\$\[\]]', text)
print(result)  # ['[', ']', '^', '$', '.', '*']
# Matches literal regex metacharacters

2. [\n\t\r] – Common whitespace characters

Description: Matches newline, tab, or carriage return characters

Example 1: Finding all whitespace characters

python

text = "Hello\tWorld\nHow are you?\rGoodbye"
result = re.findall(r'[\n\t\r]', text)
print(result)  # ['\t', '\n', '\r']
# Matches tab, newline, and carriage return
print("Whitespace count:", len(result))  # Whitespace count: 3

Example 2: Normalizing different line endings

python

text = "Line 1\r\nLine 2\nLine 3\rLine 4"
# Replace different line endings with Unix-style \n
normalized = re.sub(r'[\r\n]+', '\n', text)
print(repr(normalized))  # 'Line 1\nLine 2\nLine 3\nLine 4'

Example 3: Counting indentation levels (tabs)

python

code = "def example():\n\tprint('Hello')\n\t\tprint('Indented')\n\treturn"
tabs = re.findall(r'\t', code)
print("Indentation levels found:", len(tabs))  # Indentation levels found: 3

Example 4: Splitting on any whitespace including newlines

python

text = "Hello\tWorld\nHow  are\ryou today?"
words = re.split(r'[\s\n\t\r]+', text)
print(words)  # ['Hello', 'World', 'How', 'are', 'you', 'today?']
# Splits on any whitespace character

3. [\x00-\x7F] – ASCII characters

Description: Matches any character in the ASCII range (0-127)

Example 1: Filter ASCII characters only

python

text = "Hello δΈ–η•Œ! 123 Γ± CafΓ©"
ascii_only = re.findall(r'[\x00-\x7F]', text)
print(''.join(ascii_only))  # "Hello ! 123  Caf"
# Removes non-ASCII characters (δΈ­ζ–‡, Γ±, Γ©)

Example 2: Validate ASCII-only text

python

def is_ascii_only(text):
    return not re.search(r'[^\x00-\x7F]', text)

print(is_ascii_only("Hello World"))      # True
print(is_ascii_only("Hello δΈ–η•Œ"))       # False
print(is_ascii_only("CafΓ©"))             # False
print(is_ascii_only("123!@#"))           # True

Example 3: Remove control characters (non-printable ASCII)

python

text = "Hello\x00World\x07\x1BTest\nNormal"
# Keep only printable ASCII (32-126)
printable = re.findall(r'[\x20-\x7E]', text)
print(''.join(printable))  # "HelloWorldTestNormal"

Example 4: Extract ASCII strings from mixed content

python

text = "ASCII: Hello, Non-ASCII: δΈ­ζ–‡, Emoji: 😊, Numbers: 123"
ascii_parts = re.findall(r'[\x20-\x7E]+', text)
print(ascii_parts)  # ['ASCII: Hello, Non-ASCII: ', ', Emoji: ', ', Numbers: 123']

4. [\u0000-\uFFFF] – Unicode characters

Description: Matches any character in the Basic Multilingual Plane (most common Unicode characters)

Example 1: Working with multilingual text

python

text = "Hello δΈ–η•Œ! 🌍 Bonjour Γ± CafΓ© πŸŽ‰"
all_chars = re.findall(r'[\u0000-\uFFFF]', text)
print(all_chars)  # ['H', 'e', 'l', 'l', 'o', ' ', 'δΈ–', 'η•Œ', '!', ' ', '🌍', ' ', 'B', 'o', 'n', 'j', 'o', 'u', 'r', ' ', 'Γ±', ' ', 'C', 'a', 'f', 'Γ©', ' ', 'πŸŽ‰']
# Matches all characters including Unicode

Example 2: Finding specific Unicode ranges

python

text = "δΈ­ζ–‡ Chinese, ζ—₯本θͺž Japanese, ν•œκ΅­μ–΄ Korean, English"
# Find CJK characters (approx range)
cjk_chars = re.findall(r'[\u4E00-\u9FFF]', text)
print(''.join(cjk_chars))  # "δΈ­ζ–‡ζ—₯本θͺžιŸ©ε›½θͺž"

Example 3: Validating Unicode input

python

def contains_unicode(text):
    return bool(re.search(r'[^\u0000-\u007F]', text))

print(contains_unicode("ASCII only"))    # False
print(contains_unicode("CafΓ©"))          # True
print(contains_unicode("Hello δΈ–η•Œ"))    # True
print(contains_unicode("123!@#"))        # False

Example 4: Extracting emojis and symbols

python

text = "I love Python! πŸπŸš€ It's amazing! πŸ’»βœ¨ 🎯"
# Approximate emoji/symbol range
symbols = re.findall(r'[\u2000-\uFFFF]', text)
print(symbols)  # ['🐍', 'πŸš€', 'πŸ’»', '✨', '🎯']
# Matches emojis and other symbols beyond basic ASCII

Bonus: Advanced Examples

Example: Mixed character class usage

python

text = "File: C:\\Users\\ζ–‡ζ‘£\\file.txt\nSize: 1.5MB\r\nUnicode: δΈ­ζ–‡ πŸŽ‰"

# Extract different components
paths = re.findall(r'[A-Z]:[\\\w\u4E00-\u9FFF]+', text)
sizes = re.findall(r'[\d.]+[A-Za-z]+', text)
unicode_content = re.findall(r'[\u4E00-\u9FFF\U0001F300-\U0001F9FF]', text)

print("Paths:", paths)            # ['C:\\Users\\ζ–‡ζ‘£\\file']
print("Sizes:", sizes)            # ['1.5MB']
print("Unicode:", unicode_content) # ['ζ–‡', 'πŸŽ‰']

Example: Cleaning text with multiple character classes

python

def clean_text(text):
    # Remove control characters but keep Unicode
    text = re.sub(r'[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]', '', text)
    # Normalize whitespace
    text = re.sub(r'[\n\t\r]+', ' ', text)
    # Remove excessive spaces
    text = re.sub(r' +', ' ', text)
    return text.strip()

dirty_text = "Hello\t\tWorld\n\n\nUnicode: δΈ­ζ–‡\r\x00Control chars"
clean = clean_text(dirty_text)
print(repr(clean))  # 'Hello World Unicode: δΈ­ζ–‡'

Example: Password complexity checker

python

def check_password_complexity(password):
    has_upper = bool(re.search(r'[A-Z]', password))
    has_lower = bool(re.search(r'[a-z]', password))
    has_digit = bool(re.search(r'[0-9]', password))
    has_special = bool(re.search(r'[^\w]', password))
    has_unicode = bool(re.search(r'[^\x00-\x7F]', password))
    
    return {
        'has_upper': has_upper,
        'has_lower': has_lower,
        'has_digit': has_digit,
        'has_special': has_special,
        'has_unicode': has_unicode,
        'is_strong': has_upper and has_lower and has_digit and len(password) >= 8
    }

print(check_password_complexity("Pass123!"))
print(check_password_complexity("password"))
print(check_password_complexity("PΓ€sswΓΆrd123!"))

Similar Posts

  • Programs

    Weekly Wages Removing Duplicates even ,odd Palindrome  Rotate list Shuffle a List Python random Module Explained with Examples The random module in Python provides functions for generating pseudo-random numbers and performing random operations. Here’s a detailed explanation with three examples for each important method: Basic Random Number Generation 1. random.random() Returns a random float between 0.0 and 1.0 python import…

  • Password Strength Checker

    python Enhanced Password Strength Checker python import re def is_strong(password): “”” Check if a password is strong based on multiple criteria. Returns (is_valid, message) tuple. “”” # Define criteria and error messages criteria = [ { ‘check’: len(password) >= 8, ‘message’: “at least 8 characters” }, { ‘check’: bool(re.search(r'[A-Z]’, password)), ‘message’: “one uppercase letter (A-Z)”…

  • Global And Local Variables

    Global Variables In Python, a global variable is a variable that is accessible throughout the entire program. It is defined outside of any function or class. This means its scope is the entire file, and any function can access and modify its value. You can use the global keyword inside a function to modify a…

  • Object: Methods and properties

    πŸš— Car Properties βš™οΈ Car Methods πŸš— Car Properties Properties are the nouns that describe a car. They are the characteristics or attributes that define a specific car’s state. Think of them as the data associated with a car object. Examples: βš™οΈ Car Methods Methods are the verbs that describe what a car can do….

  • Β List ComprehensionsΒ 

    List Comprehensions in Python (Basic) with Examples List comprehensions provide a concise way to create lists in Python. They are more readable and often faster than using loops. Basic Syntax: python [expression for item in iterable if condition] Example 1: Simple List Comprehension Create a list of squares from 0 to 9. Using Loop: python…

Leave a Reply

Your email address will not be published. Required fields are marked *