本文介绍了正则表达式:只匹配一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含多个 ip 地址的字符串以及一些随机的东西.比如这个:
21/Jun/2018:01:15:38 +0000 188.79.169.152 157.52.69.50 443 - - GET/157.52.69.30 157.52.69.10
得到这个正则表达式:
[0-9]+(?:\.[0-9]+){3}
问题是这匹配多次,但我不需要那个.这个正则表达式缺少什么,所以它只会匹配一次?
谢谢,
解决方案
您可以使用 re.match
从字符串的开头匹配 ptrn因此,只需在模式的开头添加一个 .*
,我们就可以匹配从字符串开头到第一个 IP 地址的所有内容
I've got a string with multiple ip addresses together with some random stuff. For example like this one:
21/Jun/2018:01:15:38 +0000 188.79.169.152 157.52.69.50 443 - - GET / 157.52.69.30 157.52.69.10
And got this regex:
[0-9]+(?:\.[0-9]+){3}
Problem is that this matches multiple times, but I don't need that. What is missing with this regex so it will only match once?
Thanks,
解决方案
You can use re.match
which matches a ptrn from the beginning of a stringSo just by adding a .*
to the start of your pattern, we can match everything from the beginning of the string to the first ip address
>>> import re
>>> s = "21/Jun/2018:01:15:38 +0000 188.79.169.152 157.52.69.50 443 - - GET / 157.52.69.30 157.52.69.10"
>>>
>>> ptrn = r'.*?([0-9]+(?:\.[0-9]+){3})'
>>> re.match(ptrn, s).groups()[0]
'188.79.169.152'
这篇关于正则表达式:只匹配一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!