re.sub用于替换python中的文本块(多行)

时间:2018-07-15 10:58:52

标签: python regex string python-3.x

我正在尝试使用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似乎没有变化。不知道我在想什么。有任何线索吗?

3 个答案:

答案 0 :(得分:0)

可能是因为括号(和)是正则表达式的元字符。

尝试将(替换为\(,将)替换为\)

或对字符串使用替换方法,例如

input_str.replace(find_str, replace_str)

答案 1 :(得分:0)

尝试一下:ABCD\s+abcd\s+(\s+[.]\sX\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*;

答案 2 :(得分:0)

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);'
相关问题