ddNip
ddNip

Reputation: 9

Regex for a letter followed by space and quotations ( ")

I'm iterating over a list of JSON objects and want to find every occurrence of any letter followed by a space and then a quotation mark so that:

MATCH: "Some words here "

NO MATCH: "Some words here"

This is what I'm trying but it does not work:

for i in range (len(json_list)):
     m = re.search('(?=[a-z])(*\s)(?=\")', json_list[i])
     print (m.group(0))

Failing as such:

Traceback (most recent call last):
  File "api_extraspace.py", line 13, in <module>
    print (m.group(0))
AttributeError: 'NoneType' object has no attribute 'group'

Upvotes: 0

Views: 76

Answers (1)

wjandrea
wjandrea

Reputation: 32954

  1. Your lookbehind is missing the less-than sign: (?=[a-z]) -> (?<=[a-z])
  2. (*\s) is invalid. I think you want \s+.

Here's a working example:

import re
for s in ['"Some words here"', '"Some words here "']:
    m = re.search('(?<=[a-z])\s+(?=")', s)
    print(repr(s), m)

Output:

'"Some words here"' None
'"Some words here "' <_sre.SRE_Match object; span=(16, 17), match=' '>

Upvotes: 2

Related Questions