Python Check if String Contain Only Defined Characters Using Regex (original) (raw)

Last Updated : 19 Nov, 2025

Given a string, the task is to check whether it contains only a specific set of allowed characters. **For example:

**Allowed characters: a-z
**Input: "hello" -> Valid
**Input: "hi!" -> Invalid

**Allowed characters: 0-9
**Input: "657" -> Valid
**Input: "72A" -> Invalid

Let’s explore different regex-based methods to perform this check in Python.

Using re.fullmatch()

fullmatch() checks if the entire string is made up of only the allowed characters. If even one invalid character appears, the match fails.

Python `

import re s = "hello123" pattern = r"[a-zA-Z0-9]+"

if re.fullmatch(pattern, s): print("Valid string") else: print("Invalid string")

`

**Explanation:

Using re.match() with ^ and $

match() begins checking from the start, so we add ^ and $ to ensure the entire string must match the allowed characters.

Python `

import re s = "Python_3" pattern = r"^[A-Za-z0-9_]+$"

if re.match(pattern, s): print("Valid string") else: print("Invalid string")

`

**Explanation:

Using re.search() to detect invalid characters

Instead of matching allowed characters, we search for characters not allowed using re.search(). If we find any such character then, invalid.

Python `

import re s = "Hello-World" invalid = r"[^A-Za-z]"

if re.search(invalid, s): print("Invalid string") else: print("Valid string")

`

**Explanation:

Using re.findall() to list invalid characters

findall() collects all invalid characters. If the result list is empty string contains only allowed characters.

Python `

import re s = "abcXYZ!@#" invalid_chars = re.findall(r"[^A-Za-z0-9]", s)

if invalid_chars: print("Invalid string:", invalid_chars) else: print("Valid string")

`

Output

Invalid string: ['!', '@', '#']

**Explanation: