简体   繁体   中英

Python - How to check if a string has wildcards or regex

I've got a field that is supposed to be regex entered by the user; however sometimes users are entering wildcards instead. I want to check if the input has wildcard and reject. Example:

Valid (contains regex only)

s = 'abc1.*r.*'

s = 'abc1.*r'

s = 'abc1.r'

Invalid (contains wildcard)

s = 'abc1 r '

s = 'abc1.*r*'

I've tried re.findall:

s = 'abc1.\*rr*.*' # String contains wildcard hence should be rejected
a = len(re.findall('\.\*', s))
b = len(re.findall('\*', s))
if a != b:
    print "reject"

Basically checking if number of .* and * are equal. If not, that means there is a '*' without a '.'

Is there a better, cleaner way of doing this?

This can be done with this regex:

[^.]\*

This regex finds a non-dot character followed by a * . If this matches anywhere, then the regex should be rejected:

if re.search(r'[^.]\*', s):
    print("Rejected!")

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