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
- Check if an URL is valid or not using Regular Expression
- Find all the numbers in a string using regular expression in Python
- How to check if a string starts with a substring using regex in Python?
- Python | Check if string ends with any string in given list
- Python | Check whether two lists follow same pattern or not
- Python - Check if string starts with any element in list
- Remove duplicate words from Sentence using Regular Expression
- Validating Roman Numerals Using Regular expression
- Python | Check whether a string is valid json or not
- Python | Check whether string contains only numbers or not
- Python - Test if all digits starts from % K digit
- Python program to check whether a number is Prime or not
- Python regex | Check whether the input is Floating point number or not
- Python - Check whether the given List forms Contiguous Distinct Sub-Array or Not
- Check whether a number has consecutive 0's in the given base or not
- Python | Insert character after every character pair
- Python program to check whether the string is Symmetrical or Palindrome
- Extracting email addresses using regular expressions in Python
- Python Program to check whether it is possible to make a divisible by 3 number using all digits in an array
- Python | Ways to check string contain all same characters
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.