我在 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'
我需要為位于 a'='和 a之間的非數字字串添加雙引號','。結果應如下所示:
'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'
我幾個小時以來一直在嘗試使用正則運算式,但變得瘋狂。歡迎任何幫助。提前謝謝你。
uj5u.com熱心網友回復:
如果您不關心處理轉義的逗號,您可以簡單地將字串拆分為逗號,然后拆分為=,根據它是否為數字來處理右側,最后加入所有內容。
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'
uj5u.com熱心網友回復:
您可以使用帶有捕獲組的模式,并在替換中使用雙引號之間的捕獲組。
=(?!\d (?:\.\d )?(?:,|$))([^",\n] )
正則運算式演示
模式匹配:
=字面匹配(?!負前瞻,斷言直接在右邊的不是\d (?:\.\d )?(?:,|$)將 1 位數字與可選的小數部分后跟,字串的任一或結尾匹配
)關閉前瞻(捕獲組 1[^",\n]匹配除",或 換行符以外的任何字符 1 次以上
)關閉第 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/393395.html
