使用正则表达式从字符串中解析另一个字符串
我需要一个正则表达式,用来从一个字符串中提取信息。
为了让你明白我的意思,想象一下下面的内容是需要解析的字符串:
"a string" ... \\"another \"string\"\\" ... "yet another \"string" ... "failed string\"
这里的“...”表示一些任意的数据。
这个正则表达式需要返回一个列表:
["a string", "another \"string\"\\", "yet another \"string"]
补充说明:注意字面上的反斜杠不会影响第二次匹配
我试过使用finditer,但它找不到重叠的匹配项,我也试过使用前瞻(?=),但也没有成功。
有人能帮忙吗?
4 个回答
0
0
1
你可以试试下面这个正则表达式,它可以匹配那些以"
开头的字符串(前面没有\
符号),一直匹配到下一个"
符号,且这个"
前面也没有\
。
(?<!\\)".*?(?<!\\)"
>>> s = r'"a string" ... "another \"string\"" ... "yet another \"string" ... "failed string\"'
>>> m = re.findall(r'".*?[^\\]"', s)
>>> m
['"a string"', '"another \\"string\\""', '"yet another \\"string"']
>>> m = re.findall(r'".*?(?<!\\)"', s)
>>> m
['"a string"', '"another \\"string\\""', '"yet another \\"string"']
>>> m = re.findall(r'(?<!\\)".*?(?<!\\)"', s)
>>> m
['"a string"', '"another \\"string\\""', '"yet another \\"string"']
更新:
>>> s = r'"a string" ... \\"another \"string\"\\" ... "yet another \"string" ... "failed string\" '
>>> m = re.findall(r'(?<!\\)".*?(?<!\\)"|(?<=\\\\)".*?\\\\"', s)
>>> m
['"a string"', '"another \\"string\\"\\\\"', '"yet another \\"string"']
>>> for i in m:
... print i
...
"a string"
"another \"string\"\\"
"yet another \"string"