簡體   English   中英

如何檢查字符串是否僅包含 python 中的特定字符?

[英]How to check if a string contains only specific characters in python?

我希望我的字符串只有 (a-zA-Z0-9@.-_) 但是在使用此代碼時:

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

它打印'okay',但我希望打印'n',因為我的字符串(e)包含'/'並且我沒有在我的正則表達式中聲明它。 我應該怎么辦? 我也使用re.match並沒有幫助我。

這里有幾個問題。 首先. -是元字符,需要用\轉義。 其次,您實際上並不需要此處的循環 - 添加*來表示任意數量的這些字符,並限定^$之間的正則表達式以表示整個字符串需要由這些字符組成:

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

if p.match(e):
    print('okay')
else:
    print('n')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM