-3

I have the following string:

str1 = "I am doing 'very well' for your info"

and I want to extract the part between the single quotes i.e. very well

How am I supposed to set my regular expression?

I tried the following but obviously it will give wrong result

import re
pt = re.compile(r'\'*\'')
m = pt.findall(str1)

Thanks

mrt
  • 339
  • 1
  • 2
  • 14

5 Answers5

4

You can use re.findall to capture the group between the single quotes:

import re
str1 = "I am doing 'very well' for your info"
data = re.findall("'(.*?)'", str1)[0]

Output:

'very well'
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
3

Another way to solve the problem with re.findall: find all sequences that begin and end with a quote, but do not contain a quote.

re.findall("'([^']*)'", str1)
DYZ
  • 55,249
  • 10
  • 64
  • 93
2

You need to place a word character and a space between the escaped single quotes.

import re
pt = re.compile(r"'([\w ]*'")
m = pt.findall(str1)
James
  • 32,991
  • 4
  • 47
  • 70
2

Is using regular expressions entirely necessary for your case? It often is but sometimes regular expressions just complicate simple string operations.

If not, you can use Python's native Split function to split the string into a list using ' as the divider and access that part of the array it creates.

str1 = "I am doing 'very well' for your info"
str2 = str1.split("'")
print(str2[1]) # should print: very well
Chase Taylor
  • 104
  • 8
0

try this

   import re
    pattern=r"'(\w.+)?'"
    str1 = "I am doing 'very well' for your info"
    print(re.findall(pattern,str1))

output:

['very well']