繁体   English   中英

正则表达式匹配以子字符串 python 开头和结尾的字符串

[英]Regex expression to match strings that start with and ends with substrings python

我正在使用漂亮的汤并将生成的汤转换为字符串,所以目前我有一整串信息。

在整个字符串段落中,我想获取以“price”开头并以“currency”结尾的子字符串的所有实例。 所以价格 - 描述在这样的模式中: "price": 123,"description":"ice-cream","currency":"CAD" ,并且这个模式在字符串段落中重复了很多次

所以像 re.findall("^"price" & "currency"$", string)? 我不熟悉正则表达式,所以我不知道如何获得正确的正则表达式。

以下是字符串段落的示例:

{“item”:”xxx”,”price":xxx,”description”:”xxx”,”currency":"USD”,”expiry”:”xxx”},{“item”:”yyy”,”price":yyy,”description”:”yyy”,”currency":"USD”,”expiry”:”yyy”},{“item”:”zzz”,”price":zzz,”description”:”zzz”,”currency":"USD”,”expiry”:”zzz”},....

重复20次。 目前,建议的正则表达式获取从第一次出现价格到最后一次出现货币的段落。 但是,我想获得每个 substring 出现的“价格....货币”

Combine Pritalgo 's answer with barmar 's comment and read https://docs.python.org/3/library/re.html and https://www.geeksforgeeks.org/regular-expression-python-examples-set- 1/

pattern = re.compile(r'"price":\s*(.*?),"')

注意非贪婪修饰符后缀? , 替换.*?之前和之后的字符串使用适当的周围字符串,如果您真的想要包含描述,请按照您的 OP 建议添加字符串“货币”。 \s*跳过可选的空格。 ()限制, matches返回的内容。

试试这个片段。 我假设您希望将货币值包含在匹配的字符串中。

import re
search_string = """
"price": 123,"description":"ice-cream","currency":"CAD",
"price": 123,"description":"ice-cream","currency":"something", "price": 123,"description":"ice-cream","currency":"something" "price": 123,"description":"ice-cream","currency":"something"
"""

pattern = re.compile(r'"price.*currency".*",?')
matches = pattern.findall(search_string)
print(matches)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM