Open In App

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

Last Updated : 18 Nov, 2025
Comments
Improve
Suggest changes
5 Likes
Like
Report

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")

Output
Valid

Explanation:

  • ([a-z]) captures the first character and .* allows anything between
  • \1 forces the ending character to match the first and |^[a-z]$ handles single-character strings

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")

Output
Valid

Explanation:

  • ^([a-z]) ensures pattern starts with a valid character
  • .*\1$ ensures the pattern ends with the same character
  • match() normally checks only from the start, but anchors enforce full-string validation
  • |^[a-z]$ handles single-character strings

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")

Output
Valid

Explanation:

  • ^[a-z]$ checks single-character strings
  • ^([a-z]).*\1$ checks multi-character strings with same start and end
  • search() returns a match if the entire regex (with anchors) fits the string

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")

Output
Valid

Explanation:

  • ^([a-z]) extracts the first character of the string and ([a-z])$ extracts the last character
  • first[0] == last[0] compares them directly
  • findall() returns lists, so we check they exist before comparison

Regular Expressions


Explore