【问题标题】:re.sub for replacing block(multi line) of text in pythonre.sub 用于替换python中的文本块(多行)
【发布时间】:2018-07-15 10:58:52
【问题描述】:

我正在尝试使用 python 替换跨越多行文本文件的文本块。这是我的输入文件的样子。

输入.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 = input_str.replace(find_str, replace_str)
  • 代码在字符串中包含缩进,但您问题中的示例数据未缩进。如果这被正确转录,则正则表达式根本不匹配。
  • @Wiktor Stribiżew:我也尝试过替换。但不幸的是,它也没有用。
  • 您使用的是 re 还是 regex 模块?见https://pypi.org/project/regex/
  • 确保替换完全相同的字符串,计算所有空格等。它会起作用。

标签: python regex string python-3.x


【解决方案1】:

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

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

或者对字符串使用replace方法,例如,

input_str.replace(find_str, replace_str)

【讨论】:

    【解决方案2】:

    试试这个: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*;
    

    【讨论】:

      【解决方案3】:
      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);'
      

      【讨论】:

        猜你喜欢
        • 2013-02-03
        • 1970-01-01
        • 2015-11-08
        • 1970-01-01
        • 1970-01-01
        • 2016-10-13
        • 2020-06-16
        • 2017-08-07
        • 1970-01-01
        相关资源
        最近更新 更多