簡體   English   中英

字符串上 substring 的正則表達式,然后替換文本

[英]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\nras = unknownsox = pie\nsox = 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.

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