首页 > 解决方案 > 正则表达式表示一个字母后跟空格和引号 (")

问题描述

我正在遍历一个 JSON 对象列表,并希望找到每个出现的任何字母,后跟一个空格,然后是一个引号,以便:

匹配: "Some words here "

不匹配: "Some words here"

这是我正在尝试的,但它不起作用:

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

这样失败:

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

标签: python

解决方案


  1. 您的lookbehind缺少小于号:(?=[a-z])->(?<=[a-z])
  2. (*\s)是无效的。我想你想要\s+

这是一个工作示例:

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

输出:

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

推荐阅读