Python 查找并替换文件中的字符串,参数是字符串被引用而不是更大字符串的一部分 [英] Python find and replace strings in files with argument that the string is quoted and not part of bigger string
问题描述
我需要解决以下问题.如果在文件中找到动态字符串,我想替换动态字符串,但前提是字符串周围有引号,无论是在它旁边还是中间最多有两个空格,并且不是更大字符串的一部分(在 python 中):
i need a solution to the following problem. I want to replace a dynamic string if found in a file but only if there are quotes surrounding the string, either next to it or with max two spaces between, and not be part of bigger string (in python) :
ori = 'testing'
rep = 'posting'
file contents:
Line1 This is one line with some words for testing purposes
Line2 this is the seconds "testing" function.
Line3 that is one more " testing" line
Line4 "testing"
Line5 " testing"
Line6 "testing "
Line7 " testing "
我正在寻找以下结果,最好使用正则表达式作为简单有效的方法,而不是单独的函数.
Im looking for the following result preferably with regex as simple and efficient way instead of a separate function.
Line1 This is one line with some words for testing purposes
Line2 this is the seconds "testing" function.
Line3 that is one more " testing" line
Line4 "posting"
Line5 " posting"
Line6 "posting "
Line7 " posting "
正则表达式魔术师可能会在这方面帮助我.
regex magicians may help me at this one.
提前致谢.
推荐答案
正则表达式将是完成此类任务的好工具.
始终注意清楚地表达它们.
正则表达式很快就会变得令人费解并且难以调试.
A regular expression would be a good tool for such a task.
Always take care to express them clearly.
Regular expressions can quickly become puzzling and hard to debug.
import re
original = 'testing'
replacement = 'posting'
line1 = 'This is one line with some words for testing purposes'
line2 = 'this is the seconds "testing" function.'
line3 = 'that is one more " testing" line'
line4 = '"testing"'
line5 = '" testing"'
line6 = '"testing "'
line7 = '" testing "'
lines = [line1, line2, line3, line4, line5, line6, line7]
starts_with_parentheses = '^"'
ends_with_parentheses = '"$'
one_space = ' {1}'
two_spaces = ' {2}'
none_one_or_two_spaces = '(|{}|{})'.format(one_space, two_spaces)
query = starts_with_parentheses \
+ none_one_or_two_spaces \
+ original \
+ none_one_or_two_spaces \
+ ends_with_parentheses
for line in lines:
match = re.search(query, line)
if match:
line = line.replace(original, replacement)
print(line)
输出:
This is one line with some words for testing purposes
this is the seconds "testing" function.
that is one more " testing" line
"posting"
" posting"
"posting "
" posting "
这篇关于Python 查找并替换文件中的字符串,参数是字符串被引用而不是更大字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!