如果在双引号内,正则表达式不匹配单引号

2024-05-17 23:49:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我还在学习正则表达式,我找不到解决问题的方法。我想匹配字符串中的所有单引号,但如果单引号位于双引号内,则不需要匹配

例如,我有一个字符串:

'['hello', "that's great", "Good to see you O'shay"]'

我希望能够匹配'hello'周围的单引号,但不能匹配嵌套在双引号内的单引号

我希望这是有道理的!提前谢谢

编辑

不匹配单引号,而是可以获得字符串,即

'['hello', "that's great", "Good to see you O'shay"]'

'[hello, that's great, Good to see you O'shay]'

不确定这会使问题变得更容易还是更难?欢迎开悟


Tags: to方法字符串you编辑hellothatshay
1条回答
网友
1楼 · 发布于 2024-05-17 23:49:32

不是纯正则表达式解决方案。主要是将管柱细分为多个部分,然后移除不需要的部分:

test = '''['hello', "that's great", "Good to see you O'shay"]'''


import re

parts = re.split(r"(\"[^\"]*\"|'[^']*')", test)

parts = [p for p in parts if p.startswith("'")]

print(parts)

相关问题 更多 >