Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match single quotes from python re

Tags:

python

How to match the following i want all the names with in the single quotes

This hasn't been much that much of a twist and turn's to 'Tom','Harry' and u know who..yes its 'rock'

How to extract the name within the single quotes only

name = re.compile(r'^\'+\w+\'')
like image 829
Rajeev Avatar asked Dec 21 '22 23:12

Rajeev


1 Answers

The following regex finds all single words enclosed in quotes:

In [6]: re.findall(r"'(\w+)'", s)
Out[6]: ['Tom', 'Harry', 'rock']

Here:

  • the ' matches a single quote;
  • the \w+ matches one or more word characters;
  • the ' matches a single quote;
  • the parentheses form a capture group: they define the part of the match that gets returned by findall().

If you only wish to find words that start with a capital letter, the regex can be modified like so:

In [7]: re.findall(r"'([A-Z]\w*)'", s)
Out[7]: ['Tom', 'Harry']
like image 135
NPE Avatar answered Jan 10 '23 01:01

NPE