<p>What follows is a regular expression I have written to match multi-line pre-processor macros in C / C++ code. I'm by no means a regular expressions guru, so I'd welcome any advice on how I can make this better.</p>

<p>Here's the regex:</p>

<pre><code>\s*#define(.*\\\n)+[\S]+(?!\\)
</code></pre>

<p>It should match all of this:</p>

<pre><code>#define foo(x) if(x) \
doSomething(x)
</code></pre>

<p>But only some of this (shouldn't match the next line of code:</p>

<pre><code>#define foo(x) if(x) \
doSomething(x)
normalCode();
</code></pre>

<p>And also shouldn't match single-line preprocessor macros.</p>

<p>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?</p>

[{'answer_id': 60723, 'author': 'Douglas Leeder', 'author_id': 3978, 'author_profile': 'https://Stackoverflow.com/users/3978', 'pm_score': 4, 'selected': True, 'text': '<p>This is a simple test program I knocked up:</p>\n\n<pre><code>#!/usr/bin/env python\n\nTEST1="""\n#include "Foo.h"\n#define bar foo\\\\\n    x\n#include "Bar.h"\n"""\n\nTEST2="""\n#define bar foo\n#define x 1 \\\\\n    12 \\\\\n    2 \\\\\\\\ 3\nFoobar\n"""\n\nTEST3="""\n#define foo(x) if(x) \\\\\ndoSomething(x)\n"""\n\nTEST4="""\n#define foo(x) if(x) \\\\\ndoSomething(x)\nnormalCode();\n"""\n\nimport re\nmatcher = re.compile(r"^[ \\t]*#define(.*\\\\\\n)+.*$",re.MULTILINE)\n\ndef extractDefines(s):\n    mo = matcher.search(s)\n    if not mo:\n        print mo\n        return\n    print mo.group(0)\n\nextractDefines(TEST1)\nextractDefines(TEST2)\nextractDefines(TEST3)\nextractDefines(TEST4)\n</code></pre>\n\n<p>The re I used:</p>\n\n<pre><code>r"^[ \\t]*#define(.*\\\\\\n)+.*$"\n</code></pre>\n\n<p>Is very similar to the one use used, the changes:</p>\n\n<ol>\n<li>[ \\t] To avoid newlines at the start\nof the define.</li>\n<li>I rely on + being\ngreedy, so I can use a simple .*$ at\nthe end to get the first line of the\ndefine that doesn\'t end with \\</li>\n</ol>\n'}, {'answer_id': 60729, 'author': 'jfs', 'author_id': 4279, 'author_profile': 'https://Stackoverflow.com/users/4279', 'pm_score': 2, 'selected': False, 'text': '<pre><code>start        = r"^\\s*#define\\s+"\ncontinuation = r"(?:.*\\\\\\n)+"\nlastline     = r".*$"\n\nre_multiline_macros = re.compile(start + continuation + lastline, \n                                 re.MULTILINE)\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/60685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1304/']