Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting string constant from source code in a string using regular expressions in Python [closed]

How can I get a string constant from source code in a string?

For example, here is the source code I am trying to process:

var v = "this is string constant + some numbers and \" is also included "

I am unable to get everything inside quotation marks. by using this regular expression: "(.*?)".

I can't get var, v, = or anything else except string character.

like image 593
Zeeshan Anjum Avatar asked Jul 10 '26 09:07

Zeeshan Anjum


2 Answers

Using lookbehind, to make sure the " is not preceded by a \

import re

data = 'var v = "this is string constant + some numbers and \" is also included "\r\nvar v = "and another \"line\" "'
matches = re.findall( r'= "(.*(?<!\\))"', data, re.I | re.M)
print(matches)

Output:

['this is string constant + some numbers and " is also included ', 'and another "line" ']
like image 175
ChaseTheSun Avatar answered Jul 11 '26 23:07

ChaseTheSun


You need to match an opening quote, then anything that's either an escaped character or a normal character (except quotes and backslashes), and then a closing quote:

"(?:\\.|[^"\\])*"
like image 37
Tim Pietzcker Avatar answered Jul 12 '26 00:07

Tim Pietzcker



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!