Python正则表达式匹配特殊字符

Ken*_*ney 1 python regex

我需要一个可以测试字符串中是否有特殊字符的函数。我目前正在使用以下功能,但没有运气:

import re

def no_special_characters(s, pat=re.compile('[@_!#$%^&*()<>?/\|}{~:]')):
  if pat.match(s):
    print(s + " has special characters")
  else:
    print(s + " has NO special characters")
Run Code Online (Sandbox Code Playgroud)

我得到以下结果:

no_special_characters('$@')  # $@ has special characters
no_special_characters('a$@') # a$@ has NO special characters
no_special_characters('$@a') # $@a has special characters
Run Code Online (Sandbox Code Playgroud)

这对我来说没有任何意义。如何测试字符串中的任何特殊字符?

Tim*_*sen 5

这里使用的问题match()是它被锚定到字符串的开头。您想要在字符串中search()任意位置查找单个特殊字符,因此请改用:

def no_special_characters(s, pat=re.compile('[@_!#$%^&*()<>?/\|}{~:]')):
    if pat.search(s):
        print(s + " has special characters")
    else:
        print(s + " has NO special characters")
Run Code Online (Sandbox Code Playgroud)

您还可以继续使用match()以下正则表达式模式:

.*[@_!#$%^&*()<>?/\|}{~:].*
Run Code Online (Sandbox Code Playgroud)