Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match uneven number of escape symbols

I need to match C++ preprocessor statements. Now, preprocessor statements may span multiple lines:

#define foobar \
    "something glorious"

This final backslash may be escaped so the following results in two separate lines:

#define foobar \\
No longer in preprocessor.

The question is how I can match the explicit line continuation efficiently. I have the following expression which I think works. Basically, it tests whether the number of backslashes is odd. Is this correct? Can it be done more efficiently?

/
    [^\\]           # Something that's not an escape character, followed by …
    (?<escape>\\*?) # … any number of escapes, …
    (?P=escape)     # … twice (i.e. an even number).
    \\ \n           # Finally, a backslash and newline.
/x

(I'm using PHP so PCRE rules apply but I'd appreciate answers in any Regex vernacular.)

like image 640
Konrad Rudolph Avatar asked Oct 17 '25 10:10

Konrad Rudolph


1 Answers

I think you're making it more difficult than it needs to be. Try this:

/
  (?<!\\)    # not preceded by a backslash
  (?:\\\\)*  # zero or more escaped backslashes
  \\ \n      # single backslash and linefeed
/x
like image 163
Alan Moore Avatar answered Oct 20 '25 01:10

Alan Moore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!