1

Input string could be :

- "his 'pet''s name is tom' and she is 2 years old"
- " '''' "
- " '' "
- "function('name', test, 'age')"

I want to get the single quote string from these inputs which may even contain '' inside the single quote string.

I tried negative lookahead (?!') to ignore the '' while matching.

 '.*?'(?!')    

I expect output of

- 'pet''s name is tom'
- ''''
- 'name' and 'age'
Arun Kumar
  • 47
  • 5

2 Answers2

0

r"'(.+?)'" To get the single quote string

import re 

tx = "his 'pet''s name is tom' and she is 2 years old"

print(re.findall(r"\'(.+?)\'",tx)) 
#output :  ['pet', 's name is tom'] 
Alaa Aqeel
  • 615
  • 8
  • 16
  • I think that to fullfill the request you should replace the "+" with a "*" inside of your regex, currently you are getting two matches, while you should get only one – DLM May 23 '19 at 10:57
  • same thing , to get only one, delete this `?` out this `["pet''s name is tom"]` – Alaa Aqeel May 23 '19 at 11:19
0

I think you may achieve that with

r"'[^']*(?:''[^']*)*'"

See the regex demo

Explanation

  • ' - a single quotation mark
  • [^']* - 0+ chars other than single quotation mark
  • (?:''[^']*)* - zero or more repetitions of
    • '' - two single quotation marks
    • [^']* - 0+ chars other than single quotation mark
  • ' - a single quotation mark

Regex graph:

enter image description here

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • @ArunKumar Glad it worked for you. Please also consider [upvoting the answer](http://meta.stackexchange.com/questions/173399/how-to-upvote-on-stack-overflow) if it turned out useful for you. – Wiktor Stribiżew May 23 '19 at 19:52