相关疑难解决方法(0)

在Python中,如何检查字符串是否只包含某些字符?

在Python中,如何检查字符串是否只包含某些字符?

我需要检查一个只包含a..z,0..9和的字符串.(期间),没有其他性格.

我可以迭代每个字符并检查字符是a ..z或0..9,或.但那会很慢.

我现在还不清楚如何使用正则表达式来完成它.

它是否正确?你能建议一个更简单的正则表达式或更有效的方法吗?

#Valid chars . a-z 0-9 
def check(test_str):
    import re
    #http://docs.python.org/library/re.html
    #re.search returns None if no position in the string matches the pattern
    #pattern to search for any character other then . a-z 0-9
    pattern = r'[^\.a-z0-9]'
    if re.search(pattern, test_str):
        #Character other then . a-z 0-9 was found
        print 'Invalid : %r' % (test_str,)
    else:
        #No character other then . a-z 0-9 was found
        print 'Valid   : %r' % (test_str,)

check(test_str='abcde.1')
check(test_str='abcde.1#')
check(test_str='ABCDE.12')
check(test_str='_-/>"!@#12345abcde<')

''' …
Run Code Online (Sandbox Code Playgroud)

python regex search character

47
推荐指数
5
解决办法
11万
查看次数

字符串只能包含A,U,G或C.

原谅这个简单化的问题,但我已经阅读了SO问题和Python文档,但仍未能解决这个问题.

如何创建Python正则表达式来测试字符串是否包含ANY,但只包含A,U,G和C字符?字符串可以包含其中一个或所有字符,但如果它包含任何其他字符,我希望正则表达式失败.

我试过了:

>>> re.match(r"[AUGC]", "AUGGAC")
<_sre.SRE_Match object at 0x104ca1850>
Run Code Online (Sandbox Code Playgroud)

但是在字符串的末尾添加一个X仍然有效,这不是我所期望的:

>>> re.match(r"[AUGC]", "AUGGACX")
<_sre.SRE_Match object at 0x104ca1850>
Run Code Online (Sandbox Code Playgroud)

提前致谢.

python regex

1
推荐指数
1
解决办法
139
查看次数

标签 统计

python ×2

regex ×2

character ×1

search ×1