我必须在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的发现,但我仅需要第二个if条件是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 )
{
...
答案 0 :(得分:1)
您可以使用
re.sub(r'(?m)^(\s*if\s*)(\(.*(?:\n(?!\s*if\s*\().*)*)//\s*(\w+)\s*$', r'\1(\2 || \3)', s)
请参见regex demo。
详细信息
(?m)
-re.M
标志^
-一行的开头(\s*if\s*)
-第1组:if
包含0+空格(\(.*(?:\n(?!\s*if\s*\().*)*)
-第2组:
\(
-一个(
.*
-该行的其余部分(?:\n(?!\s*if\s*\().*)*
-重复0次或更多次
\n(?!\s*if\s*\()
-换行符LF,后面没有if
并用0+空格括起来,然后是(
.*
-该行的其余部分//\s*
-//
和0+空格(\w+)
-第3组:1个或更多单词字符\s*$
-0 +空格和行尾。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)
{
...
答案 1 :(得分:0)
正则表达式捕获匹配的第一个模式。这就是为什么它总是从第一个if
开始。
考虑以下最小示例,其中非贪婪的?
不会修改输出:
>>> re.compile(r"if(.*?)XYZ").search("if a if b if c XYZ").group(1)
' a if b if c '
但是,非贪婪的?
确实会修改输出:
>>> re.compile(r"if(.*?)XYZ").search("if a XYZ if b if c XYZ").group(1)
' a '
非贪婪的?
仅在搜索的右侧起作用。