首页 > 解决方案 > 正则表达式匹配可能包含 ''' '' ''' 的单引号字符串

问题描述

输入字符串可以是:

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

我想从这些输入中获取单引号字符串,这些输入甚至可能包含''在单引号字符串中。

我尝试否定前瞻(?!')来忽略''while 匹配。

 '.*?'(?!')    

我期望输出

- 'pet''s name is tom'
- ''''
- 'name' and 'age'

标签: pythonregex

解决方案


r"'(.+?)'"获取单引号字符串

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'] 

推荐阅读