首页 > 解决方案 > 如何在python中使用带有字符异常的多行DOTALL

问题描述

我必须在 python 中找到多行模式。所以我正在使用正则表达式中的 DOTALL,但它发现的不仅仅是我需要的。

示例文件:

if(condition_1)
{
....
some text
some text

if ((condition_1== condition_2)   ||
                 (condition_3== condition_4) ||
           (condition_6== condition_5)  ||
     (condition_7== condition_8)   ) // XYZ_variable
{
...

我的 python 正则表达式如下

re.compile(r'(if\s*?\()(.*?)(\/\/\s*?)(XYZ_variable)', re.DOTALL)

这是从第一个 if 条件直到 XYZ_variable 找到的,但如果存在 XYZ_variable 的条件,我只需要第二个。

所以我按如下方式更改了我的正则表达式,这不起作用

re.compile(r'(if\s*?\()([^\{].*?)(\/\/\s*?)(XYZ_variable)', re.DOTALL)

我的最终输出应该是

if(condition_1)
    {
    ....
    some text
    some text

    if (((condition_1== condition_2)   ||
                     (condition_3== condition_4) ||
               (condition_6== condition_5)  ||
         (condition_7== condition_8)   ) || XYZ_variable )
    {
    ...

但我的正则表达式做了这样的事情

if ((condition_1)
        {
        ....
        some text
        some text

        if ((condition_1== condition_2)   ||
                         (condition_3== condition_4) ||
                   (condition_6== condition_5)  ||
             (condition_7== condition_8)   ) || XYZ_variable )
        {
        ...

标签: pythonregexpython-3.x

解决方案


您可以使用

re.sub(r'(?m)^(\s*if\s*)(\(.*(?:\n(?!\s*if\s*\().*)*)//\s*(\w+)\s*$', r'\1(\2 || \3)', s)

请参阅正则表达式演示

细节

  • (?m)-re.M标志
  • ^- 一行的开始
  • (\s*if\s*)- 第 1 组:if包含 0+ 个空格
  • (\(.*(?:\n(?!\s*if\s*\().*)*)- 第 2 组:
    • \(- 一个(
    • .*- 线路的其余部分
    • (?:\n(?!\s*if\s*\().*)*- 0次或多次重复
      • \n(?!\s*if\s*\()- 换行符 LF,后面不跟if0+ 个空格,然后跟(
      • .*- 线路的其余部分
  • //\s*-//和 0+ 个空格
  • (\w+)- 第 3 组:1 个或多个单词字符
  • \s*$- 0+ 个空格和行尾。

Python演示

import re
s = """if(condition_1)
{
....
some text
some text

if ((condition_1== condition_2)   ||
                 (condition_3== condition_4) ||
           (condition_6== condition_5)  ||
     (condition_7== condition_8)   ) // XYZ_variable
{
..."""
print( re.sub(r'(?m)^(\s*if\s*)(\(.*(?:\n(?!\s*if\s*\().*)*)//\s*(\w+)\s*$', r'\1(\2 || \3)', s) ) 

输出:

if(condition_1)
{
....
some text
some text

if (((condition_1== condition_2)   ||
                 (condition_3== condition_4) ||
           (condition_6== condition_5)  ||
     (condition_7== condition_8)   )  || XYZ_variable)
{
...

推荐阅读