【发布时间】:2014-06-14 20:40:52
【问题描述】:
我正在尝试让re.search 查找其中没有字母 p 的字符串。我的正则表达式代码返回列表中我不想要的所有内容。我写了一个替代解决方案,它给了我想要的确切结果,但我想看看这是否可以用re.search 解决,但我也会接受另一个正则表达式解决方案。我也试过re.findall,但没有用,re.match 也不起作用,因为它会在字符串的开头查找模式。
import re
someList = ['python', 'ppython', 'ython', 'cython', '.python', '.ythop', 'zython', 'cpython', 'www.python.org', 'xyzthon', 'perl', 'javap', 'c++']
# this returns everything from the source list which is what I DON'T want
pattern = re.compile('[^p]')
result = []
for word in someList:
if pattern.search(word):
result.append(word)
print '\n', result
''' ['python', 'ppython', 'ython', 'cython', '.python', '.ythop', 'zython', 'cpython', 'www.python.org', 'xyzthon', 'perl', 'javap', 'c++'] '''
# this non regex solution returns the results I want
cnt = 0; no_p = []
for word in someList:
for letter in word:
if letter == 'p':
cnt += 1
pass
if cnt == 0:
no_p.append(word)
cnt = 0
print '\n', no_p
''' ['ython', 'cython', 'zython', 'xyzthon', 'c++'] '''
【问题讨论】:
标签: regex python-2.7 regex-negation