Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 
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'

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 
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

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

question from:https://stackoverflow.com/questions/65640798/python-regex-extracting-texts-between-single-or-double-quotation-marks

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
325 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

for match in re.finditer(r'^(['"])(.*?(?:(?<!['"])
)?.*?)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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...