创建 Python 正则表达式以匹配字符串

Creating a Python Regex to match a string

提问人:Bruce Banner 提问时间:10/26/2023 更新时间:10/26/2023 访问量:87

问:

我很难为此字符串创建正则表达式。我需要:

  1. 提取 Property 后面的单词,直到 &
  2. 提取 Category, until & 之后的单词
  3. 创建一个正则表达式以匹配从 “cat” 到 “modifiedBy” 之前的所有内容
"cat":"Property : TikTok Videos & Category : Insta Videos & User Impact: TBD & User Minutes :
18","modifiedBy"

我目前的正则表达式是:

"cat":"Property : (?P<property>\w+.*?) & Category : (?P<category>\w+)?

  1. 这能够将“属性”正确地命名为“TikTok 视频”。

  2. 但是命名的“类别”正则表达式只是“Insta”一词。 如果我在 (?P\w+,那么它最终会一直消耗到字符串的末尾。

  3. 至于消耗从“cat”到“modified”之前的最后一个逗号的整个字符串,我不知道如何捕获它。

因此,最终产品将是:

  1. 属性 = TIkTok 视频
  2. 类别 = Insta 视频
  3. Entire_string = “cat”:“属性 : TikTok 视频 & 类别 : Insta 视频 & 用户影响: 待定 & 用户分钟数 : 18”
python-3.x 正则表达式组

评论

4赞 Barmar 10/26/2023
这看起来像是 JSON 的一部分。为什么不使用json.loads()
0赞 Barmar 10/26/2023
\w+将只匹配一个单词,因为它不匹配空格。为什么不像你之后那样捕获多个单词呢?Property:
0赞 Bruce Banner 10/26/2023
它是 JSON,但它嵌套在许多层中,我不知道如何在 JSON 中用不同的键值对替换键值对。所以我想如果我把它作为一个字符串读进去,然后在它上面使用“re”,可能会更容易。
0赞 Barmar 10/26/2023
只需使用嵌套字典访问即可。foo['bar']['baz'] = new value

答:

1赞 Reilas 10/26/2023 #1

'...提取 Property 后面的单词,直到 & ...提取 Category, until & ...' 之后的单词

(?:Property|Category)\W+(.+?) *&

或者,更准确地说。

(?:Property|Category) *: *(.+?) *&

'...创建一个正则表达式来匹配从 “cat” 到 , 在 “modifiedBy” 之前的所有内容......

。至于消耗从“cat”到“modified”之前的最后一个逗号的整个字符串,我不知道如何捕获它。...'

若要匹配该值,请使用环视语法

(?s)\"cat\":.+?(?=,\"modifiedBy\")

而且,要获取价值,只需提供文本即可。

(?s)(\"cat\" *: *.+?),\"modifiedBy\"

下面是一个示例。

s = '"cat":"Property : TikTok Videos & Category : Insta Videos & User Impact: TBD & User Minutes :\n' \
    '18","modifiedBy"'
for m in re.finditer('(?:Property|Category) *: *(.+?) *&', s):
    print(f"'{m.group(1)}'")
for m in re.finditer(r'(?s)\"cat\":.+?(?=,\"modifiedBy\")', s):
    print(f"'{m.group()}'")

输出

'TikTok Videos'
'Insta Videos'
'"cat":"Property : TikTok Videos & Category : Insta Videos & User Impact: TBD & User Minutes :
18"'
0赞 sln 10/26/2023 #2

您可以使用前瞻断言使用单个正则表达式完成所有操作。

r'(?s)^(?=.*?Property\s*:\s*(?P<Property>[^&]*?)\s*&)(?=.*?Category\s*:\s*(?P<Catggory>[^&]*?)\s*&)(?=.*?(?P<cat>"cat".*?"),\s*"modifiedBy")'

https://regex101.com/r/gdM2q1/1

扩展/格式化

(?s)
^
(?=
   .*? Property \s* : \s* 
   (?P<Property> [^&]*? )        # (1)
   \s* &
)
(?=
   .*? Category \s* : \s* 
   (?P<Catggory> [^&]*? )        # (2)
   \s* &
)
(?=
   .*? 
   (?P<cat> "cat" .*? " )        # (3)
   , \s* "modifiedBy"
)

如果您需要使用文本,请使用此文本。
这样做是为了将当前位置移动到最后一组“类别”和“属性”文本之外(
尽管不能保证)。您还需要向其添加多行修饰符。
"cat"m(?sm)

r'(?sm)^(?=.*?Property\s*:\s*(?P<Property>[^&]*?)\s*&)(?=.*?Category\s*:\s*(?P<Catggory>[^&]*?)\s*&).*?(?P<cat>"cat".*?"),\s*"modifiedBy"'

https://regex101.com/r/tZEm5K/1