Python – Check whether a string starts and ends with the same character or not (using Regular Expression)
Given a string. The task is to write a regular expression to check whether a string starts and ends with the same character.
The input can be divide into 2 cases:
- Single character string: All single character strings satisfies the condition that they start and end with the same character. The regex for a string with only 1 character will be-
- Multiple character string: Here we need to check whether the first and the last character is same or not. We do this using \1. The regex will be-
The two regular expressions can be combined using |
In this program, we will use search() method of re module.
Below is the implementation.
Time Complexity : O(n), where n is length of string
Auxiliary Space : O(1)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses
are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!