单词不以字母开头
问题描述:
我有一个字符串“one two 9three 52eight four”,所以我只想得到“one two four”,因为“three”以“9”开始,“eight”以“ 52" 。单词不以字母开头
我想:
"(?!\d)\w+"
,但它仍然以 “三化” 和 “八”。我不想要它。
答
尝试
\b[a-zA-Z]\w*
答
正常工作对我来说:
import re
l = "one two 9three 52eight four".split()
c = re.compile("(?!\d)\w+")
m = [w for w in l if re.match(c, w)]
print m
打印:
['one', 'two', 'four']
答
这是因为\w
包括数。你需要做的是:
>>> s = "one two 9three 52eight four"
>>> import re
>>> re.findall(r'\b[a-z]+\b', s, re.I)
['one', 'two', 'four']
而且,你正在使用(?!...)
称为负先行,而你可能是指负向后看(?<!...)
,这当然会仍然失败,因为上面提到的问题。
ETA:那么你只需要一个字边界:
>>> re.findall(r'\b(?!\d)\w+', s)
['one', 'two', 'four']
答
正则表达式可能是矫枉过正。
In [3]: [word for word in eg.split(' ') if not word[0].isdigit()]
Out[3]: ['one', 'two', 'four']
谢谢。这一个正在工作。 – pocoa 2010-04-28 14:18:14
这绝对是正确的答案+1包括小写字母和大写字母 – ant 2010-04-28 14:19:10
@ c0mrade:并且哪个答案不是? – SilentGhost 2010-04-28 14:21:31