[英]re.sub for replacing block(multi line) of text in python
我正在嘗試使用python替換跨越文本文件多行的文本塊。 這是我的輸入文件的樣子。
input.txt:
ABCD abcd (
. X (x),
.Y (y)
);
ABCD1 abcd1 (
. X1 (x1),
.Y1 (y1)
);
我正在讀取具有以下代碼的上述文件,並嘗試替換文本,但未成功。 下面是我的代碼。
fo = open(input.txt, 'r')
input_str = fo.read()
find_str = '''ABCD abcd (
.X (x),
.Y (y)
);'''
replace_str = '''ABCDE abcde (
. XX (xx),
.YY (yy)
);'''
input_str = re.sub(find_str, replace_str, input_str)
但是input_str似乎沒有變化。 不知道我在想什么。 有什么線索嗎?
可能是因為括號(和)是正則表達式的元字符。
嘗試用(
用\\(
和)
替換為\\)
。
或對字符串使用替換方法,例如,
input_str.replace(find_str, replace_str)
試試這個: ABCD \\ s + abcd \\ s +(\\ s + [。] \\ s X \\ s (x)\\ s *,\\ s * [。] Y \\ s *(y)\\ s *)\\ s *;
ABCD
\s+ #(1 or more 'spaces' (space, tab, new line...))
abcd
\s+
\( # left parenthesis, you need to scape this because
# parenthesis mean 'capturin group' in a regexp
\s+
[.] # Dot means 'any single character but new line' on a regexp
# so you need to scape it with either \. or [.]
\s*X\s* # (\s* means 0 or more spaces)
\(x\)
\s*,\s*
[.]Y\s*
\(y\)
\s*\)\s*;
re.sub("([.]\\s*)(\\w+)(.*?)(\\w+)","\\1\\2\\2\\3\\4\\4",fo)
Out[412]: 'ABCD abcd (\n . XX (xx),\n .YY (yy)\n);\nABCD1 abcd1 (\n . X1X1 (x1x1),\n .Y1Y1 (y1y1)\n);'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.