![]() |
VOOZH | about |
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.
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.
Valid
Explanation:
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.
Valid
Explanation:
search() checks anywhere in the string, but since our pattern already uses ^ and $, it still validates the full string correctly.
Valid
Explanation:
We extract the first and last characters using two small regex patterns and compare them manually.
Valid
Explanation: