Python Check Whether a String Starts and Ends with the Same Character or Not (using Regular Expression) (original) (raw)

Last Updated : 18 Nov, 2025

Given a string, the task is to check whether its first and last characters are the same using regular expressions. **For example:

**Input: abba **Output: Valid
**Input: a **Output: Valid
**Input: abc **Output: Invalid

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

Using re.fullmatch() with a Backreference

fullmatch() checks if the entire string follows the regex. We capture the first character, allow anything in between, and use \1 to ensure the last character is the same.

Python `

import re s = "abba" pattern = r"^([a-z]).*\1$|^[a-z]$"

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

`

**Explanation:

Using re.match() with Anchors ^ and $

match() checks from the start of the string. By adding ^ at the beginning and $ at the end, we ensure that the entire string must follow the same backreference pattern.

Python `

import re s = "abba" pattern = r"^([a-z]).*\1$|^[a-z]$"

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

`

**Explanation:

Using re.search() With Combined Pattern

search() checks anywhere in the string, but since our pattern already uses ^ and $, it still validates the full string correctly.

Python `

import re s = "abba" pattern = r"^[a-z]$|^([a-z]).*\1$"

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

`

**Explanation:

Using re.findall()

We extract the first and last characters using two small regex patterns and compare them manually.

Python `

import re

s = "abba" first = re.findall(r'^([a-z])', s) last = re.findall(r'([a-z])$', s)

if first and last and first[0] == last[0]: print("Valid") else: print("Invalid")

`

**Explanation:

Regular Expressions