Reputation: 1055
I am using the below code:
email = "yash@"
string_check= re.compile('[@.]')
if(string_check.search(email) == None):
print('invalid')
else:
print('valid')
This rightly evaluates to 'valid'. However, if I want to ensure that the string strictly contains both '@' and '.' then what is the way in which I can achieve it?
I have also tried below code but it does not work with special charcaters:
import re
arr = ['@', '.']
# str = "hello people"
str = "yash"
if any(re.findall('|'.join(arr), str)):
print('Found a match')
else:
print('No match found')
This evaluates to "Found a match" despite having neither "@" nor "."
Upvotes: 1
Views: 30
Reputation: 15364
The solution provided by @Andrej Kesely does work, but the complexity could be much much better. His solution has a complexity of O(mn), where m is the length of arr
and n is the length of email
. Here is an alternative solution (might look worse, but it has a better complexity):
from collections import Counter
counter = Counter(email)
if all(counter[ch] > 0 for ch in arr):
print('valid')
else:
print('non valid')
Here the complexity is O(max(m, n))
Upvotes: 0
Reputation: 195468
You can use all()
function, no need to use regex:
arr = ['@', '.']
email = "yash@"
if all(ch in email for ch in arr):
print('valid')
else:
print('not valid')
Prints:
not valid
Upvotes: 2