规则的表达总是不给任何东西

2024-04-19 01:23:09 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码

>>> ll = 'window.DETAILS_PAGE_MAP_GLOBALS = {GOOGLE_MAPS_LONGITUDE: 55.2378015294,GOOGLE_MAPS_LATITUDE: 25.0463764816}'
>>> print(re.match('GOOGLE_MAPS_LATITUDE:\s*(\d+\.\d+)', ll))
None

我总是得到None尽管我100%确信正则表达式是正确的。

你能帮忙吗?你知道吗


Tags: renone密码mapmatchgooglepagedetails
2条回答

使用^{}而不是re.match();后者只匹配字符串开头的

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance.

演示:

>>> import re
>>> ll = 'window.DETAILS_PAGE_MAP_GLOBALS = {GOOGLE_MAPS_LONGITUDE: 55.2378015294,GOOGLE_MAPS_LATITUDE: 25.0463764816}'
>>> re.match('GOOGLE_MAPS_LATITUDE:\s*(\d+\.\d+)', ll)
>>> re.search('GOOGLE_MAPS_LATITUDE:\s*(\d+\.\d+)', ll)
<_sre.SRE_Match object at 0x105525cd8>
>>> re.search('GOOGLE_MAPS_LATITUDE:\s*(\d+\.\d+)', ll).group(1)
'25.0463764816'

您需要使用re.search()而不是re.match()。第一个是查找字符串中任何位置的模式,另一个是查找模式是否可以准确地应用于字符串。你知道吗

From the documentation

re.search(pattern, string, flags=0)

Scan through string looking for a location where the regular expression pattern produces a match, and return a corresponding match object. Return Noneif no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

示例:

>>> print(re.search('GOOGLE_MAPS_LATITUDE:\s*(\d+\.\d+)', ll))
<_sre.SRE_Match object at 0xffecf260>
>>> print(re.search('GOOGLE_MAPS_LATITUDE:\s*(\d+\.\d+)', ll).groups())
('25.0463764816',)
>>> print(re.search('GOOGLE_MAPS_LATITUDE:\s*(\d+\.\d+)', ll).group(1))
25.0463764816

相关问题 更多 >