我必须在 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 )
{
...
您可以使用
re.sub(r'(?m)^(\s*if\s*)(\(.*(?:\n(?!\s*if\s*\().*)*)//\s*(\w+)\s*$', r'\1(\2 || \3)', s)
See the 正则表达式演示 https://regex101.com/r/eDvGHp/2/.
Details
-
(?m)
- re.M
flag
-
^
- 一行的开头
-
(\s*if\s*)
- 第 1 组:if
包含 0+ 个空格
-
(\(.*(?:\n(?!\s*if\s*\().*)*)
- Group 2:
-
\(
- a (
-
.*
- 该行的其余部分
-
(?:\n(?!\s*if\s*\().*)*
- 0 or more repetitions of
-
\n(?!\s*if\s*\()
- 换行符 LF,后面不跟if
用 0+ 空格括起来,然后是(
-
.*
- 该行的其余部分
-
//\s*
- //
和 0+ 空格
-
(\w+)
- 第 3 组:1 个或多个单词字符
-
\s*$
- 0+ 空格和行尾。
Python演示 https://rextester.com/XPON48451:
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) )
Output:
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)
{
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)