【问题标题】:How to replace multiple values in matching pattern from string如何从字符串替换匹配模式中的多个值
【发布时间】:2019-04-20 16:18:09
【问题描述】:

我想在字符串中搜索一个模式,然后再次在匹配模式中搜索一些无效字符,然后将它们删除或替换为一些有效字符。

我有一些示例字典,例如。 sample_dict = {"randomId":"123y" uhnb\n g", "desc": ["sample description"]}

在这种情况下,我想找到字典的值,比如“123y”uhnb\n g”,然后删除其中的无效字符,例如 (", \t, \n) 等。 我尝试将所有字典存储在一个文件中,然后读取文件和匹配模式以获取字典值,但这给了我一个匹配模式列表,我也可以编译这些匹配项,但我不确定如何在原始字典中执行替换值,所以我的最终输出将是: {"randomId":"123y uhnb g", "desc": ["sample description"]}

pattern = re.findall("\":\"(.+?)\"", sample_dict)

预期结果:

{"randomId":"123y uhnb g", "desc": ["sample description"]}

实际结果:

['123y" uhnb\n g']

【问题讨论】:

  • 不要使用正则表达式解析 JSON,使用 JSON 解析器
  • Parse JSON in Python的可能重复
  • @miken32:我可以使用 json 解析器,但在这种情况下,我也需要删除那些无效字符,否则它将不起作用,所以为了删除这些字符,我正在使用正则表达式。跨度>
  • 你是怎么得到这个奇怪的sample_dict 的?也许您可以早点避免这种情况,这样您就不需要替换或删除奇怪的字符。
  • 你为什么使用 re.findall 而不是 re.sub(以某种能力)?

标签: python regex


【解决方案1】:

您可以使用 re.sub 在您的值中替换非字母数字字符 如下

dct = {"randomId":"123y uhnb\n g", "desc": ["sample description"]}
import re

for key, value in dct.items():
    val = None
    #If the value is a string, directly substitute
    if isinstance(value, str):
       val = re.sub(r"[^a-zA-Z0-9 ]", '', str(value))
    #If value is a list, substitute for all string in the list
    elif isinstance(value, list):
       val = []
       for item in value:
           val.append(re.sub(r"[^a-zA-Z0-9]", ' ', str(item)))
    dct[key] = val

print(dct)
#{'randomId': '123y uhnb g', 'desc': ['sample description']}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 2014-03-22
    • 2014-09-03
    • 2014-05-28
    相关资源
    最近更新 更多