编写正则表达式跳过含特定字符的行?
我正在尝试在Python中写一个正则表达式,用来解析一个文件,文件内容大概是这样的:
static const PropertyID PROPERTY_X = 10225;
//static const PropertyID PROPERTY_Y = 10226;
//static const PropertyID PROPERTY_Z = 10227;
我想提取属性名称和数字,但只针对没有被注释的属性。 这是我写的表达式:
tuples = re.findall(r"[^/]*static[ \t]*const[ \t]*PropertyID[ \t]*(\w+)[ \t]*=[ \t]*(\d+).*",fileContents)
这里的fileContents是文件内容的字符串形式。
但是这个正则表达式竟然还匹配到了被注释的行(以//开头的行)。我该如何让它不匹配这些注释行呢?
3 个回答
0
如果你在解析C语言代码,可以使用类似于 pycparser 这样的工具。正则表达式并不适合(或者说无法)解析任何编程语言。
另外,我觉得下面这段代码对于你要做的事情来说更简单:
import re
string = " //static const PropertyID PROPERTY_Z = 10227;"
results = re.split("\s*",string)
#results = ['//static', 'const', 'PropertyID', 'PROPERTY_Z', '=', '10227;']
if results[0].startswith("\\") or results[0].startswith("/*"):
pass
2
试试这个:
r"(?m)^(?!//)static\s+const\s+PropertyID\s+(\S+)\s+=\s+(\d+);"
几点说明:
^ 表示行的开头
(?!//) 是一种负向前瞻,意思是后面不能跟着 //
\s 代表任何空格字符
\S 代表任何非空格字符
1
你可以指定,在行的开头之后,你只想要在第一个 static
之前留空格:
tuples = re.findall(r"^\s*static[ \t]*const[ \t]*PropertyID[ \t]*(\w+)[ \t]*=[ \t]*(\d+).*",fileContents)