python - 如何在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 )
{
...
解决方案
您可以使用
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,后面不跟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)
{
...
推荐阅读
- java - 如何防止从 close_wait 连接打开太多文件
- amazon-web-services - AWS Dynamo DB:在 GSI 上使用查询的高读取延迟
- java - 检查不同类的 ArrayList 中是否存在值而不创建新列表
- vue.js - 你如何在 vuex 中正确地调度一个动作?在 Chrome 中获取错误 [vuex] 未知操作类型
- git - 将存储库镜像到另一个存储库中的子文件夹
- node.js - 在 linux nodejs 上获取 USB 打印机的状态
- javascript - 识别 jQuery 中的 HTML 下拉选择
- php - 如何在 PHP 7.4 中分配多维数组?
- reactjs - Material-UI Dialog背景阴影在某些情况下闪烁
- javascript - 我使用了 post 方法仍然出现错误