【问题标题】:How to add double quotes to sequence of char inside a string如何在字符串中的字符序列中添加双引号
【发布时间】:2022-01-23 20:19:09
【问题描述】:

我在 Python 中有一个类似的字符串:

'speed=36.2448,course=331.35,gps_time=2021-11-22T00:43:22.678Z,fix=1,message_source=device_gps,period_km=0.436,location=Middle of no where,x=3.2'

我需要为位于'='',' 之间的非数字字符串添加双引号。结果应如下所示:

'speed=36.2448,course=331.35,gps_time="2021-11-22T00:43:22.678Z",fix=1,message_source="device_gps",period_km=0.436,location="Middle of no where",x=3.2'

我从几个小时就开始尝试使用正则表达式,但变得疯狂。 欢迎任何帮助。提前谢谢你。

【问题讨论】:

  • 你确定逗号是分隔符吗? IIRC,您可以使用反斜杠转义行协议中的逗号,以使它们成为文字逗号。你想处理这个案子还是不会有问题?你试过什么正则表达式,它出了什么问题?
  • 你想做到多一般?是否总是相同的 name=value 对,用逗号分隔。

标签: python string


【解决方案1】:

如果您不关心处理转义的逗号,您可以简单地将字符串拆分为逗号,然后拆分=,根据是否为数字处理右侧,最后加入所有内容。

s = 'speed=36.2448,course=331.35,gps_time=2021-11-22T00:43:22.678Z,fix=1,message_source=device_gps,period_km=0.436,location=Middle of no where,x=3.2'

items = []
for item in s.split(','):
    lhs, rhs = item.split('=', 1)
    try:
        float(rhs)
        # Could convert rhs to float, so leave item unchanged
        items.append(item)
    except ValueError:
        # Could not convert rhs to float, so is not numeric. Surround rhs with quotes
        items.append(f'{lhs}="{rhs}"')

modified_s = ",".join(items)

给了

modified_s = 'speed=36.2448,course=331.35,gps_time="2021-11-22T00:43:22.678Z",fix=1,message_source="device_gps",period_km=0.436,location="Middle of no where",x=3.2'

【讨论】:

    【解决方案2】:

    您可以使用带有捕获组的模式,并在替换中使用双引号之间的捕获组。

    =(?!\d+(?:\.\d+)?(?:,|$))([^",\n]+)
    

    Regex demo

    模式匹配:

    • = 字面匹配
    • (?!负前瞻,断言右边的不是
      • \d+(?:\.\d+)?(?:,|$) 匹配 1+ 位,可选小数部分后跟 , 或字符串结尾
    • ) 关闭前瞻
    • ( 捕获第 1 组
      • [^",\n]+ 匹配除 " , 或换行符以外的任何字符 1 次以上
    • )关闭第一组

    例如

    import re
    
    regex = r"=(?!\d+(?:\.\d+)?(?:,|$))([^\",\n]+)"
    s = 'speed=36.2448,course=331.35,gps_time=2021-11-22T00:43:22.678Z,fix=1,message_source=device_gps,period_km=0.436,location=Middle of no where,x=3.2'
    result = re.sub(regex, r'="\1"', s)
    print(result)
    

    输出

    speed=36.2448,course=331.35,gps_time="2021-11-22T00:43:22.678Z",fix=1,message_source="device_gps",period_km=0.436,location="Middle of no where",x=3.2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-19
      相关资源
      最近更新 更多