1

I want my string only have (a-zA-Z0-9@.-_) but when using this code:

import re
e='p12/5@gmail.com'
p=re.compile(r'[a-zA-Z0-9@.-_]')
for ele in e:
    if bool(p.search(ele)):
        print('okay')
    else:
        print('n')

it prints 'okay' but I expect to print 'n' because my string(e) contains '/' and I didn't declare it on my regex. what should I do? I also used re.match and didn't help me either.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
parsap1378
  • 55
  • 5

1 Answers1

3

There are a couple of issues here. First . and - are meta-characters, and need to escaped with a \. Second, you don't really need the loop here - add a * to indicate any number of these characters, and qualify the regex between ^ and $ to signify the entire string needs to be made up of these characters:

import re
e = 'p12/5@gmail.com'
p = re.compile(r'^[a-zA-Z0-9@\.\-_]*$')

if p.match(e):
    print('okay')
else:
    print('n')
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 1
    Oh I didn't know about meta-characters. anything other than alphabets and numbers is meta-character? – parsap1378 Jan 01 '21 at 22:35
  • 1
    @parsap1378 You can find a full list with explanations about all the special characters in `re`'s documentation: https://docs.python.org/3/library/re.html – Mureinik Jan 01 '21 at 22:38