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

问题描述 投票:0回答:1

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

  1. 提取Property后面的单词,直到&
  2. 提取Category后面的单词,直到&
  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 Videos”。

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

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

所以最终产品将是:

  1. 属性 = TIkTok 视频
  2. 类别 = Insta 视频
  3. Entire_string = "cat":"属性:TikTok 视频和类别:Insta 视频和用户影响:待定和用户分钟数:18"
python-3.x regex regex-group
1个回答
-1
投票

创建匹配表达式;如果匹配,则分配值。

代码:

import re

input_str = '"cat":"Property : TikTok Videos & Category : Insta Videos & User Impact: TBD & User Minutes : 18","modifiedBy"'

property_match = re.search(r'Property : (?P<property>[^&]+)', input_str)
category_match = re.search(r'Category : (?P<category>[^&]+)', input_str)
entire_string_match = re.search(r'"cat":"(.*?)(?=,\"modifiedBy)', input_str)

# Check if matches
if property_match:
    property_value = property_match.group('property').strip()
else:
    property_value = None

if category_match:
    category_value = category_match.group('category').strip()
else:
    category_value = None

if entire_string_match:
    entire_string = entire_string_match.group(1)
else:
    entire_string = None

print("Property:", property_value)
print("Category:", category_value)
print("Entire String:", entire_string)

输出:

Property: TikTok Videos
Category: Insta Videos
Entire String: Property : TikTok Videos & Category : Insta Videos & User Impact: TBD & User Minutes : 18"
© www.soinside.com 2019 - 2024. All rights reserved.