[英]python regex to match multi-line preprocessor macro
What follows is a regular expression I have written to match multi-line pre-processor macros in C / C++ code. 以下是我编写的正则表达式,用于匹配C / C ++代码中的多行预处理器宏。 I'm by no means a regular expressions guru, so I'd welcome any advice on how I can make this better.
我绝不是一名正则表达大师,所以我欢迎任何关于我如何能做得更好的建议。
Here's the regex: 这是正则表达式:
\s*#define(.*\\\n)+[\S]+(?!\\)
It should match all of this: 它应该匹配所有这些:
#define foo(x) if(x) \
doSomething(x)
But only some of this (shouldn't match the next line of code: 但只有一部分(不应该匹配下一行代码:
#define foo(x) if(x) \
doSomething(x)
normalCode();
And also shouldn't match single-line preprocessor macros. 并且也不应该匹配单行预处理器宏。
I'm pretty sure that the regex above works - but as I said, there probably a better way of doing it, and I imagine that there are ways of breaking it. 我很确定上面的正则表达式有效 - 但正如我所说,可能有更好的方法,我想有办法打破它。 Can anyone suggest any?
任何人都可以建议吗?
This is a simple test program I knocked up: 这是一个简单的测试程序,我敲了一下:
#!/usr/bin/env python
TEST1="""
#include "Foo.h"
#define bar foo\\
x
#include "Bar.h"
"""
TEST2="""
#define bar foo
#define x 1 \\
12 \\
2 \\\\ 3
Foobar
"""
TEST3="""
#define foo(x) if(x) \\
doSomething(x)
"""
TEST4="""
#define foo(x) if(x) \\
doSomething(x)
normalCode();
"""
import re
matcher = re.compile(r"^[ \t]*#define(.*\\\n)+.*$",re.MULTILINE)
def extractDefines(s):
mo = matcher.search(s)
if not mo:
print mo
return
print mo.group(0)
extractDefines(TEST1)
extractDefines(TEST2)
extractDefines(TEST3)
extractDefines(TEST4)
The re I used: 我用过的:
r"^[ \t]*#define(.*\\\n)+.*$"
Is very similar to the one use used, the changes: 非常类似于使用的一种用法,改变:
start = r"^\s*#define\s+"
continuation = r"(?:.*\\\n)+"
lastline = r".*$"
re_multiline_macros = re.compile(start + continuation + lastline,
re.MULTILINE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.