How to match special symbols at start, end and middle of a string? I know, that I should use regex. For example I made a function:
def check_word(word: str) -> bool:
special_symbols = '()1234567890!?_@#$%^&*.,'
e = re.match(special_symbols, word) # How to match symbols at end?
m = re.match(special_symbols, word) # How to match symbols at middle?
s = re.match(special_symbols, word) # How to match symbols at start?
if e is not None:
return True
if m is not None:
return True
if s is not None:
return True
if e is not None and s is not None:
return False
if s is not None and m is not None:
return False
print(check_word("terdsa223124")) # --> True
print(check_word("ter223124dsa")) # --> True
print(check_word("223124terdsa")) # --> True
print(check_word("223124terdsa223124")) # --> False
print(check_word("223124ter223124dsa")) # --> False
How to fill re.match
so that printing was correct?
You can easily implement it without regex based on arithmetic operations on booleans:
import itertools
def check_word(word):
spec_symbols = '()1234567890!?_@#$%^&*.,'
match = [l in spec_symbols for l in word]
group = [k for k,g in itertools.groupby(match)]
return sum(group) == 1
print(check_word("terdsa223124")) # True
print(check_word("ter223124dsa")) # True
print(check_word("223124terdsa")) # True
print(check_word("223124terdsa223124")) # False
print(check_word("223124ter223124dsa")) # False
You can try this:
import re
a = ["terdsa223124", "ter223124dsa", "223124terdsa", "223124terdsa223124"]
final_output = {s:any([re.findall('^[\d\W]+[a-zA-Z]+$', s), re.findall('^[a-zA-Z]+[\d\W]+[a-zA-Z]+$', s), re.findall('^[a-zA-Z]+[\d\W]+$', s)]) for s in a}
Output:
{'223124terdsa223124': False, '223124terdsa': True, 'terdsa223124': True, 'ter223124dsa': True}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.