Search for special characters in a string

How to combine special characters at the beginning, end and middle of a line? I know that I have to 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.matchso that the seal is correct?

+4
source share
2 answers

You can easily implement it without regular expression 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
+3
source

You can try the following:

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}

Conclusion:

{'223124terdsa223124': False, '223124terdsa': True, 'terdsa223124': True, 'ter223124dsa': True}
+2
source

Source: https://habr.com/ru/post/1688528/


All Articles