Python Regex to find a string in double quotes within a string


A code in python using regex that can perform something like this

Input: Regex should return "String 1" or "String 2" or "String3" 
Output: String 1,String2,String3


3/1/2012 4:12:29 PM

Accepted Answer

Here's all you need to do:

def doit(text):      
  import re
  # matches is now ['String 1', 'String 2', 'String3']
  return ",".join(matches)

doit('Regex should return "String 1" or "String 2" or "String3" ')
# result:
'String 1,String 2,String3'

As pointed out by Li-aung Yip: (I nearly quote)

.+? is the "non-greedy" version of .+. It makes the regular expression match the smallest number of characters it can instead of the most characters it can. The greedy version, .+, will give string 1" or "String 2" or "String 3; the non-greedy version .+? 'String 1,String 2,String3'

In addition (Johan speaking again), if you want to accept empty strings, change .+ to .*. Star means zero or more - plus means at least one.

3/1/2012 5:04:29 PM

Just try to fetch double quoted strings from the multiline string:

import re

"my name is daniel"  "mobile 8531111453733"[[[[[[--"i like pandas"
"location chennai"! -asfas"aadhaar du2mmy8969769##69869" 
@4343453 "pincode 642002""@mango,@apple,@berry" 

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow