1

I'm attempting to match multiline strings in C code via the re module.

I'd like to match strings of the form:

char * theString = "Some string \
                   I want to match.";

I tried the following regex, which does not work:

regex = re.compile(r"\".*\"$", re.MULTILINE)

I thought that it would match the first ", then continue searching the next line until it found a closing ", but this is not the case. Is this because $ requires that there be a " at the end of the line to match? Is there some way to do this using regex?

0

1 Answer 1

1

Use dot all flag.

However, this is the way to parse C strings. (?s)"[^"\\]*(?:\\.[^"\\]*)*"

if it doesn't support (?s) inline modifier, set the modifier in the flags parameter.

re.compile(r'"[^"\\]*(?:\\.[^"\\]*)*"', re.DOTALL)

 (?s)
 "
 [^"\\]*                       # Double quoted text
 (?: \\ . [^"\\]* )*
 "

Ideally, you should add (raw regex) (?<!\\)(?:\\\\)* at the beginning,
to make sure the opening double quote is not escaped.

Sign up to request clarification or add additional context in comments.

8 Comments

@ sln Using that expression in re.compile((?s)"[^"\]*(?:\\.[^"\]*)*") produces a syntax error. Have I used it incorrectly? I'm new to python regex.
@VictorBrunell - You could use the raw syntax, or just a normal double quoted string "(?s)\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"" Is it a language parse syntax error I presume? If its a regex syntax error, it might not like the modifier (?s) in which case take it out and use the DOTALL flag from the options.
@ sln re.compile("(?s)\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"") returns no match as well unfortunately.
re.compile(r'"[^"\\]*(?:\\.[^"\\]*)*"', re.DOTALL)
@ sln When running that against the lines in my original post via print myregex.findall(line) it still returns [], where myregex = re.compile(r'"[^"\\]*(?:\\.[^"\\]*)*"', re.DOTALL)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.