0
votes

What I want to do is to extract all values between single or double quotation marks.

Let's say I have the following values.

"Alice's Adventures in Wonderland 1" 
"Alice's 'Adventures' in Wonderland 1" 
"Alice's "Adventures" in Wonderland 1" 
"Alice's Adventures \nin Wonderland 1" 
'Alice's Adventures in Wonderland 1'
'Alice's "Adventures" in Wonderland 1'
'Alice's 'Adventures' in Wonderland 1'
'Alice's Adventures \tin Wonderland 1'

And the desired outputs are:

Alice's Adventures in Wonderland 1
Alice's 'Adventures' in Wonderland 1
Alice's "Adventures" in Wonderland 1
Alice's Adventures \nin Wonderland 1
Alice's Adventures in Wonderland 1
Alice's "Adventures" in Wonderland 1
Alice's 'Adventures' in Wonderland 1
Alice's Adventures \tin Wonderland 1

How should I write the regex (using one regex expression for extracting all the desired values at once) to get the whole texts enclosed in the first and last quotation marks ?

p.s. I want to use re.search(r"...", text) method

1
Is your question how to handle scenarios where there is a single or double quote in the middle of your desired string? - M Z
Getting group 1 with pattern r'"(.*)"' should just work. - kwkt
@MZ yes and also \ (back slash) - Hari Jinn
@kwkt that only works for some of the values. I want to extract all the desired values at one time in this case. - Hari Jinn
@HariJinn Given your examples: (?:'(.*)'|\"(.*)\") works for me. But note that this won't work with the multiline flag, or if there are multiple examples on the same line - M Z

1 Answers

0
votes

(?<![\'\"])\n)? part to include \ns coming in between the actual text. \1 towards the end to match with quotation it started with ' or "

for match in re.finditer(r'^([\'\"])(.*?(?:(?<![\'\"])\n)?.*?)\1 *$', str1, re.M):
    print(match.group(2))

Alice's Adventures in Wonderland 1
Alice's 'Adventures' in Wonderland 1
Alice's "Adventures" in Wonderland 1
Alice's Adventures 
in Wonderland 1
Alice's Adventures in Wonderland 1
Alice's "Adventures" in Wonderland 1
Alice's 'Adventures' in Wonderland 1
Alice's Adventures  in Wonderland 1