簡體   English   中英

為什么我的正則表達式不匹配?

[英]Why is my Regular Expression not matching?

我有以下模式:

find_pattern = re.compile(r'(ga:country:\s)([a-zA-Z()\s]*)(.*users:\s)(\d+),')

這是應該匹配的輸入的樣子:

        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,

這就是 output 的格式化方式(以防它為問題增加任何價值):

        ['(not set)', 60],
        ['Albania', 7],

當我運行測試時:

matches = find_pattern.finditer(self.data)
print('matches:', matches)
for match in matches:
    print(match)

找不到匹配項。

希望有人能夠提供幫助。

我建議使用 2 個捕獲組而不是 4 個,在ga:之后添加可選的空白字符,並在users:

.*也可以是非貪婪的.*? 獲得第一個以防有更多users:零件。

為了防止users:開始一個更大的詞的一部分,你可以讓它更具體地匹配:users:

\bga:\s*country:\s*([a-zA-Z()\s]*),.*?:users:(\d+)

正則表達式演示

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

[('(not set)', '60'), ('Albania', '7'), ('Algeria', '10'), ('Argentina', '61'), ('Armenia', '2')]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM