![](/img/trans.png)
[英]Remove repeating special characters using regular expression if present alone but not when surrounded by words or numbers
[英]Regular expression to check whether one or more special characters are present in string
我正在使用以下代碼:
email = "yash@"
string_check= re.compile('[@.]')
if(string_check.search(email) == None):
print('invalid')
else:
print('valid')
這正確地評估為“有效”。 但是,如果我想確保字符串嚴格包含“@”和“。” 那么我可以通過什么方式實現它?
我也嘗試過下面的代碼,但它不適用於特殊字符:
import re
arr = ['@', '.']
# str = "hello people"
str = "yash"
if any(re.findall('|'.join(arr), str)):
print('Found a match')
else:
print('No match found')
盡管既沒有“@”也沒有“。”,這評估為“找到匹配項”。
您可以使用all()
function,無需使用正則表達式:
arr = ['@', '.']
email = "yash@"
if all(ch in email for ch in arr):
print('valid')
else:
print('not valid')
印刷:
not valid
@Andrej Kesely 提供的解決方案確實有效,但復雜性可能要好得多。 他的解決方案的復雜度為 O(mn),其中 m 是arr
的長度,n 是email
的長度。 這是一個替代解決方案(可能看起來更糟,但它具有更好的復雜性):
from collections import Counter
counter = Counter(email)
if all(counter[ch] > 0 for ch in arr):
print('valid')
else:
print('non valid')
這里的復雜度是 O(max(m, n))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.