find = re.compile("^(.*)\..*")
for l in lines:
m = re.match(find, l)
print m.group(1)
我想对字符串中的任何内容进行正则表达式,直到第一个点为止。
在[email protected]
,我想a@b
在[email protected]
,我想a@b
在[email protected]
,我想a@b
我的代码给了我...
[email protected]
版画 a@b
[email protected]
版画 [email protected]
[email protected]
版画 [email protected]
应该找到什么,以便只得到a @ b?
默认情况下,所有量词本质上都是贪婪的。从某种意义上说,他们将尝试消耗尽可能多的字符串。您可以在它们?
后添加一个使它们不愿意:
find = re.compile(r"^(.*?)\..*")
如评论中所述,如果您的字符串中没有句点,则此方法将失败。因此,这取决于您希望它如何表现。但是,如果要在这种情况下获取完整的字符串,则可以使用否定的字符类:
find = re.compile(r"^([^.]*).*")
遇到第一个句点或字符串结尾时,它将自动停止。
另外,您也不想使用re。match()
那里。回覆。search()
应该很好。您可以将代码修改为:
find = re.compile(r"^[^.]*")
for l in lines:
print re.search(find, l).group(0)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句