[英]Why is my Regular Expression not matching?
I have the following pattern:我有以下模式:
find_pattern = re.compile(r'(ga:country:\s)([a-zA-Z()\s]*)(.*users:\s)(\d+),')
This is how the input that should be matched looks like:这是应该匹配的输入的样子:
ga:country: (not set),Date range:0,ga:users:60,
ga:country: Albania,Date range:0,ga:users:7,
ga:country: Algeria,Date range:0,ga:users:10,
...
ga:country: Argentina,Date range:0,ga:users:61,
ga:country: Armenia,Date range:0,ga:users:2,
And this is how the output is going to be formatted (in case it adds any value to the question):这就是 output 的格式化方式(以防它为问题增加任何价值):
['(not set)', 60],
['Albania', 7],
And when I run a test:当我运行测试时:
matches = find_pattern.finditer(self.data)
print('matches:', matches)
for match in matches:
print(match)
No matches are found.找不到匹配项。
Hope someone is able to help.希望有人能够提供帮助。
I would suggest using 2 capturing groups instead of 4, add optional whitespace chars after ga:
and make the whitspace chars optional after users:
我建议使用 2 个捕获组而不是 4 个,在
ga:
之后添加可选的空白字符,并在users:
The .*
could also be non greedy .*?
.*
也可以是非贪婪的.*?
to get the first one in case there are more users:
parts.获得第一个以防有更多
users:
零件。
To prevent users:
begin part of a larger word, you could make it more specific matching :users:
为了防止
users:
开始一个更大的词的一部分,你可以让它更具体地匹配:users:
\bga:\s*country:\s*([a-zA-Z()\s]*),.*?:users:(\d+)
Example with re.findall that returns the values of the capturing groups: re.findall 的示例返回捕获组的值:
import re
regex = r"\bga:\s*country:\s*([a-zA-Z()\s]*),.*?:users:(\d+)"
s = ("ga:country: (not set),Date range:0,ga:users:60,\n"
"ga:country: Albania,Date range:0,ga:users:7,\n"
"ga:country: Algeria,Date range:0,ga:users:10,\n"
"ga:country: Argentina,Date range:0,ga:users:61,\n"
"ga:country: Armenia,Date range:0,ga:users:2,")
print(re.findall(regex, s))
Output Output
[('(not set)', '60'), ('Albania', '7'), ('Algeria', '10'), ('Argentina', '61'), ('Armenia', '2')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.