How to match a single character in python using Regular Expression?

A single character can be matched in Python using a regular expression. A regular expression is a sequence of characters that helps you find a string or a set of strings using a search pattern. Regular expressions are also known as RegEx. Python provides the re module that is used to work with regular expressions.

The Dot (.) Metacharacter

The dot . is a special metacharacter in regular expressions that matches any single character except newline. It's the most common way to match a single character in a pattern.

Using findall() Function

The findall() function searches for strings matching the specified pattern in the given string and returns all matches as a list of strings.

Syntax

re.findall(pattern, string)

Example 1: Matching Three-Character Words Ending with "at"

In this example, we search for any three-character sequence ending with "at" using the pattern .at ?

import re

string = 'oats cat pan'
result = re.findall(r'.at', string)
print(result)
['oat', 'cat']

Example 2: Matching Every Single Character

To match and extract every single character in a string, use the dot pattern . ?

import re

text = 'Python program'
characters = re.findall(r'.', text)
print('Single characters:', characters)
Single characters: ['P', 'y', 't', 'h', 'o', 'n', ' ', 'p', 'r', 'o', 'g', 'r', 'a', 'm']

Example 3: Finding Words with Specific Pattern

This example finds three-character words with "u" as the middle character using the pattern .u. ?

import re

string = 'man men sun run fun'
matches = re.findall(r'.u.', string)
print(matches)
['sun', 'run', 'fun']

Example 4: Matching Words Ending with "an"

Find any three-letter word ending with "an" from the given string ?

import re

text = 'fan can ran tan plan'
matches = re.findall(r'.an', text)
print('Matched words:', matches)
Matched words: ['fan', 'can', 'ran', 'tan']

Note: The word "plan" doesn't match because .an only matches three characters, while "plan" has four characters.

Example 5: Including Special Characters

The dot metacharacter matches any character including spaces and punctuation marks ?

import re

sentence = 'AI is fun!'
characters = re.findall(r'.', sentence)
print('Characters found:', characters)
Characters found: ['A', 'I', ' ', 'i', 's', ' ', 'f', 'u', 'n', '!']

Key Points

  • The . matches any single character except newline
  • Use findall() to get all matches as a list
  • Raw strings (r'') are recommended for regex patterns
  • The dot includes spaces and special characters in matches

Conclusion

The dot metacharacter . is essential for matching single characters in Python regular expressions. Combined with findall(), it provides a powerful way to extract character patterns from strings.

Updated on: 2026-03-24T18:56:28+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements