簡體   English   中英

Re.sub對我不起作用

[英]Re.sub not working for me

我正在嘗試讓re.sub用例如值替換指定的模式

for lines in f:
    pattern='\${2}'+key[0]+'\${2}'
    re.search(pattern,lines)

這將返回找到模式的行。 例如,如果得到了這是測試返回值之一

這是$$ test $$

我遇到的問題是當我執行以下操作時

re.sub(pattern,key[1],lines)

什么都沒發生。 我想念什么? 有關更多信息, key[0]=testkey[1]=replace所以我想做的就是每當遇到“ $$ test $$”時,它將用“ replace”代替。 我沒有發現“ $$ test $$”的問題,但是由於某種原因, re.sub沒有取代它。

正在re.sub的結果分配回一個變量,對嗎? 例如

lines = re.sub(pattern, key[1], lines)

這是一個字符串,因此無法更改(Python中的字符串是不可變的),因此將創建一個新字符串並將其返回給您。 如果不將其分配回名稱,則會丟失該名稱。

如果有文本,則可以直接在整個文本上運行re.sub(),如下所示:

import re

ss = '''that's a line
another line
a line to $$test$$
123456
here $$test$$ again
closing line'''

print(ss,'\n')

key = {0:'test', 1:'replace'}

regx = re.compile('\$\${[0]}\$\$'.format(key))

print( regx.sub(key[1],ss) )

如果您讀取文件,則應該在運行re.sub()之前先讀取整個文件並將其放入對象ss中 ,而不是逐行讀取和替換

並且,如果您有行的列表,則必須按以下步驟處理:

import re

key = {0:'test', 1:'replace'}

regx = re.compile('\$\${[0]}\$\$'.format(key))

lines = ["that's a line",
         'another line',
         'a line to $$test$$',
         '123456',
         'here $$test$$ again',
         'closing line']

for i,line in enumerate(lines):
    lines[i] =  regx.sub(key[1],line)

否則,包含“ $$ test $$”的行將不會被修改:

import re

key = {0:'test', 1:'replace'}

regx = re.compile('\$\${[0]}\$\$'.format(key))

lines = ["that's a line",
         'another line',
         'a line to $$test$$',
         '123456',
         'here $$test$$ again',
         'closing line']

for line in lines:
    line =  regx.sub(key[1],line)


print (lines)

結果

["that's a line", 'another line', 'a line to $$test$$', '123456', 'here $$test$$ again', 'closing line']

暫無
暫無

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

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