Given a string. The task is to write a regular expression to check whether a string starts and ends with the same character.
Input : abba Output : Valid Input : a Output : Valid Input : abc Output : Invalid
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.
Valid Valid Invalid
- Find all the numbers in a string using regular expression in Python
- Python - Check if string starts with any element in list
- Python | Check if string ends with any string in given list
- Check if an URL is valid or not using Regular Expression
- Regular Expression in Python with Examples | Set 1
- Python | Check order of character in string using OrderedDict( )
- Validating Roman Numerals Using Regular expression
- Remove duplicate words from Sentence using Regular Expression
- Program to check if a string contains any special character
- Python - Evaluate Expression given in String
- How to capitalize first character of string in Python
- Python | K Character Split String
- Python - Lowercase Kth Character in string
- Python | Frequency of each character in String
- Python | Lowercase first character of String
- Python - Least Frequent Character in String
- Python | Longest Run of given Character in String
- Check the equality of integer division and math.floor() of Regular division in Python
- Python - Group list by first character of string
- Python - Split String of list on K character
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.