匹配regex python

时间:2017-12-31 19:44:02

标签: python regex

我是新的python编程。在使用正则表达式匹配字符串后,我一直在尝试查找一些数据。

例如:

str1 = 'ethernet33 20628103568 111111 22222222222 '

我只是在寻找' 20628103568'但是使用我的代码,它会在ethernet33之后打印所有内容

这是代码

match1 = re.search("(?<=ethernet33\s).*(?<=\s)", str1)
print match1.group()

输出:

20628103568 111111 22222222222

预期产出:

20628103568 

非常感谢有关如何修改上述正则表达式以实现此目的的任何指导

2 个答案:

答案 0 :(得分:2)

你应该使用这个正则表达式:

>>> import re

#          to match only the digits with  v
#    your "positive lookbehind assertion" v
>>> match1 = re.search('(?<=^ethernet33\s)\d+', str1)
#                           ^ to just match the pattern at the start of string.
#                           ^ prevents additional traversals
>>> match1.group()
'20628103568'

答案 1 :(得分:0)

在您的情况下,我认为str1.split()[1]可能会有所帮助

相关问题