6
votes

How to get what is between the quotes in the following two texts ?

text_1 = r""" "Some text on \"two\" lines with a backslash escaped\\" \
     + "Another text on \"three\" lines" """

text_2 = r""" "Some text on \"two\" lines with a backslash escaped\\" + "Another text on \"three\" lines" """

The problem for me is that the quotes should be ignored if they are escaped, but there is the possibilty to have the backslash escaped.

I would like to obtain the following groups.

[
    r'Some text on \"two\" lines with a backslash escaped\\',
    r'Another text on \"three\" lines'
]
4
Sorry I've edited my question because some spurious spaces have been added by the google translator. - user1054158
You'll need more escapes there. Why the concatenation in the middle? That just distracts from your question - Martijn Pieters♦
I've also forgotten the escaped quotes, that has been done. - user1054158
@MartijnPieters Your're right. Here is now the simpler version of my uqestion. - user1054158
There is nothing to ignore? I don't see any escaped - jamylak

4 Answers

21
votes
"(?:\\.|[^"\\])*"

matches a quoted string, including any escaped characters that occur within it.

Explanation:

"       # Match a quote.
(?:     # Either match...
 \\.    # an escaped character
|       # or
 [^"\\] # any character except quote or backslash.
)*      # Repeat any number of times.
"       # Match another quote.
1
votes
>>> import re
>>> text = "Some text on\n\"two\"lines" + "Another texton\n\"three\"\nlines"
>>> re.findall(r'"(.*)"', text)
["two", "three"]
1
votes

Match everything but a double quote:

import re
text = "Some text on \"two\" lines" + "Another text on \"three\" lines"
print re.findall(r'"([^"]*)"', text)

Output

['two', 'three']
0
votes
>>> import re
>>> text_1 = r""" "Some text on \"two\" lines with a backslash escaped\\" \
     + "Another text on \"three\" lines" """
>>> text_2 = r""" "Some text on \"two\" lines with a backslash escaped\\" + "Another text on \"three\" lines" """
>>> re.findall(r'\\"([^"]+)\\"', text_2)
['two', 'three']
>>> re.findall(r'\\"([^"]+)\\"', text_1)
['two', 'three']

Perhaps you want this:

re.findall(r'\\"((?:(?<!\\)[^"])+)\\"', text)