我正在编写一个Python脚本来识别在哪里清理一些C++代码。我想不出一个正则表达式来检测include语句中反斜杠的使用,但是忽略恰好使用反斜杠的字符串中反斜杠的使用。
每一行都以一个六位数字开头,这是原始文件中的行号。下面是一个例子,我遇到的问题是字符串中的\n, \t and \"
导致匹配为假阳性:
000001#include "should\be\no\backslashes"
000002 QString code =
000003 "#include <QPushButton>\n#include \"some/thing\"\n{\n\tauto button = new QPushButton(parent);\n\tButtonStyle::ApplyButtonStyling(*button);\n}\n";
正则表达式应该使用组来匹配行号和匹配的文本。
什么正则表达式可以与第一行的include
匹配,但又能防止包含include
和反斜杠的转义序列的字符串出现误报?
发布于 2018-06-16 04:56:49
以下是最终对我起作用的方法:
regex = r'^(?P<line_num>\d{6})(?P<line>.*#include\s+(\".*\\.*\"|<.*\\.*>).*$)'
发布于 2018-06-01 02:39:36
为什么不在正则表达式中包含#include
,以便只在include语句中搜索反斜杠?
下面的正则表达式匹配字符串开头的6位数字,如果它后面跟一个#include
(在它和数字之间只有空格),并且字符串中其他地方至少有一个反斜杠。它与第三个字符串不匹配,因为数字和#include
之间的"
破坏了模式
r'^(\d{6})\s*(?=#include.*\\)'
此示例返回所需的结果:
import re
strings = [r'000001#include "should\benobackslashes"', r'000002 QString code =', r'000003 "#include <QPushButton>\n#include \"some/thing\"\n{\n\tauto button = new QPushButton(parent);\n\tButtonStyle::ApplyButtonStyling(*button);\n}\n";']
for string in strings:
m = re.search(r'(\d{6})(?=#include.*\\)', string)
try:
print(m.group(0))
except:
pass
输出:
000001
虽然你的问题可能比这更复杂,但基于你的问题,我认为基于这一点的简单方法应该是可行的。
https://stackoverflow.com/questions/50630388
复制相似问题