在字符串中查找特殊符号

时间:2017-11-01 13:17:21

标签: python python-3.x

如何在字符串的开头,结尾和中间匹配特殊符号? 我知道,我应该使用正则表达式。例如,我做了一个函数:

    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

如何填写re.match以便打印正确?

2 个答案:

答案 0 :(得分:3)

您可以根据对布尔值的算术运算,在没有正则表达式的情况下轻松实现它:

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

答案 1 :(得分:2)

你可以试试这个:

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}

输出:

{'223124terdsa223124': False, '223124terdsa': True, 'terdsa223124': True, 'ter223124dsa': True}