[英]regex for substring on a string then replace text
我有一個我正在閱讀的文本文件:
with open(file,'r+') as f:
file_data = f.read()
file_data
是一個長字符串,包含以下文本:
'''This file starts here dig_1 = hello\n doge ras = friend\n sox = pie\n'''
我想搜索dig_1
然后獲取'='
之后的所有文本直到換行符\n
並將其替換為不同的文本,以便它是dig_1 = hello\n
現在是dig_1 = unknown
並執行相同的操作其他人( ras = friend\n
到ras = unknown
和sox = pie\n
到sox = unknown
)。 有沒有一種簡單的方法可以使用正則表達式來做到這一點?
您可以使用 python 的re
模塊的sub
function
您要替換的模式看起來像一個單詞,后跟等號和空格,並且前面還有一個換行符
# import re module
import re
# original text
txt = '''This file starts here dig_1 = hello\n doge ras = friend\n sox = pie\n'''
# pattern to look for
pattern = '= (.*?\n)'
# string to replace with
repl = 'unknown'
# replace 'pattern' with the string inside 'repl' in the string 'txt'
re.sub(pattern, repl, txt)
'This file starts here dig_1 unknown doge ras unknown sox unknown'
你可以在這里使用re.sub
:
inp = "This file starts here dig_1 = hello\n doge ras = friend\n sox = pie\n"
output = re.sub(r'\b(\S+)\s*=\s*.*(?=\n|$)', r'\1 = unknown', inp)
print(output)
這打印:
This file starts here dig_1 = unknown
doge ras = unknown
sox = unknown
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.