简体   繁体   中英

Python Regex Match Special Characters

I need a function that can test whether a string has any special characters in it. I'm currently using the following function with no luck:

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")

I get the following results:

no_special_characters('$@')  # $@ has special characters
no_special_characters('a$@') # a$@ has NO special characters
no_special_characters('$@a') # $@a has special characters

This doesn't make any sense to me. How can I test for ANY special characters in a string?

The problem with using match() here is that it is anchored to the beginning of the string. You want to find a single special character anywhere in the string, so use search() instead:

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

You could also keep using match() with the following regex pattern:

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

使用search功能代替match功能。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM