Regular expression practice
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama" Output: true
Example 2:
Input: "race a car" Output: false
I know the concept of regular expression, however, I barely use this concept when I develop. I think I need more practice using regular expression so I brought this question from Leetcode.
import re
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = re.sub(r'[^\w]','',s)
s = s.lower()
return s == s[::-1]
* re.sub(pattern, repl, string, count=0, flags=0)
* r'[^\w]': [ ] -> Used to indicate a set of characters / \w -> For Unicode (str) patterns:
reference site : https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/883/discuss/219018/Fast-Python-Regular-Expression(Cheated...)
https://docs.python.org/3.2/library/re.html