我很难为这个字符串创建正则表达式。我需要:
"cat":"Property : TikTok Videos & Category : Insta Videos & User Impact: TBD & User Minutes :
18","modifiedBy"
我当前的正则表达式是:
"cat":"Property : (?P<property>\w+.*?) & Category : (?P<category>\w+)?
这可以将“财产”正确命名为“TikTok Videos”。
但是命名的“类别”正则表达式只是单词“Insta”。 如果我像 (?P\w+ 一样添加一个 +,那么它最终会一直消耗到字符串末尾。
至于消耗从“cat”到“modified”之前的最后一个逗号的整个字符串,我不知道如何捕获它。
所以最终产品将是:
创建匹配表达式;如果匹配,则分配值。
代码:
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"