Open In App

Python Regex | Program to Accept String Ending with Alphanumeric Character

Last Updated : 15 Nov, 2025
Comments
Improve
Suggest changes
3 Likes
Like
Report

Given a string, the task is to check whether it ends with an alphanumeric character (A–Z, a–z, 0–9). For example:

Input: hello123 -> Accept
Input: hello@ -> Discard

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

Using re.fullmatch()

fullmatch() ensures the entire string must follow the regex pattern. We allow any characters before the end and enforce that the last character must be alphanumeric.

Python
import re
text = "hello123"
pattern = r".*[A-Za-z0-9]$"

if re.fullmatch(pattern, text):
    print("Accept")
else:
    print("Discard")

Output
Accept

Explanation:

  • .* matches any characters from start
  • [A-Za-z0-9]$ ensures the final character is alphanumeric
  • re.fullmatch() validates the entire string, not just part of it

Using re.match() with ^ and $ Anchors

match() starts checking from the beginning, so adding start (^) and end ($) anchors forces a full-string match.

Python
import re
text = "hello123"
pattern = r"^.*[A-Za-z0-9]$"

if re.match(pattern, text):
    print("Accept")
else:
    print("Discard")

Output
Accept

Explanation:

  • ^ anchors at start and .* allows anything in the middle
  • [A-Za-z0-9]$ final character must be alphanumeric
  • re.match() + anchors acts like full-string validation

Using re.search()

search() scans the whole string, but since the regex ends with $, it only matches if the very last character is alphanumeric.

Python
import re
text = "hello123"
pattern = r"[A-Za-z0-9]$"

if re.search(pattern, text):
    print("Accept")
else:
    print("Discard")

Output
Accept

Explanation:

  • [A-Za-z0-9]$ checks the character right before the end
  • re.search() searches anywhere but $ restricts it to the string end

Using re.findall()

findall() returns all matches. Here it extracts only the last character if it is alphanumeric.

Python
import re
text = "hello123"
last_char = re.findall(r"[A-Za-z0-9]$", text)

if last_char:
    print("Accept")
else:
    print("Discard")

Output
Accept

Explanation:

  • [A-Za-z0-9]$ captures the last alphanumeric char, if present
  • findall() returns a list; non-empty list means valid end

Explore