簡體   English   中英

正則表達式替換無法用正則表達式變量替換 Python

[英]regex replace unable to substitute in Python with regex variables

我們有大量文件需要轉換為 json 這是一個文件的示例數據

{
1=2,
4=tt,
6=9
}
{
1=gg,
2=bd,
6=bb
}

我正在使用 python 轉換正則表達式工作正常的數據,但是當我在 python 代碼中實現時,相同的正則表達式不起作用

import numpy as np
f = open('/Users/rahulvarma/Downloads/2020120911.txt', 'r')
content = f.read()
import re
regex = r"([0-9]+)(=)((.*)+)"
subst = "\"$1\":\"$3\","
result = re.sub(regex, subst, content,  0, re.MULTILINE)

if result:
    print (result)

但我是

{
"$1":"$3",
"$1":"$3",
"$1":"$3"
}
{
"$1":"$3",
"$1":"$3",
"$1":"$3"
}

我預期的 output 應該是

{
"1":"2",
"4":"tt",
"6":"9"
}
{
"1":"gg",
"2":"bd",
"6":"bb"
}

您可以使用此正則表達式進行搜索:

(\d+)=([^,\n]*)(,|$)

並替換使用:

"\1":"\2"\3

正則表達式演示

代碼:

regex = r"(\d+)=([^,\n]*)(,|$)"

result = re.sub(regex, r'"\1":"\2"\3', input_str, 0, re.MULTILINE)

正則表達式詳細信息:

  • (\d+) :匹配捕獲組#1 中的 1+ 個數字
  • = : 匹配=字符
  • ([^,\n]*) : 匹配 0 個或多個不是,而不是\n在捕獲組 #2 中的任何字符
  • (,|$) : 匹配捕獲組 #3 中的逗號或行尾

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM