Python Regex | Program to Accept String Ending with Alphanumeric Character (original) (raw)

Last Updated : 15 Nov, 2025

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

`

**Explanation:

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

`

**Explanation:

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

`

**Explanation:

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

`

**Explanation: