使用正则表达式从字符串中解析字符串

时间:2014-08-31 00:48:58

标签: python regex

我需要一个将从字符串中解析字符串的正则表达式。

为了向您展示我的意思,请设想以下是要解析的字符串的内容

"a string" ... \\"another \"string\"\\" ... "yet another \"string" ... "failed string\" 

其中" ..."表示一些任意数据。

正则表达式需要返回列表:

["a string", "another \"string\"\\", "yet another \"string"] 

修改:请注意,字面反斜杠不会停止第二场比赛

我已经尝试过发现者,但它没有找到重叠的匹配,我尝试了前瞻(?=),但我也无法让它发挥作用。

帮助?

4 个答案:

答案 0 :(得分:1)

您可以尝试使用以下正则表达式将以"开头的字符串(前面没有\符号)的字符串匹配到下一个"符号其中也没有\

(?<!\\)".*?(?<!\\)"

DEMO

>>> 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"

DEMO

答案 1 :(得分:0)

您可以使用此正则表达式:

"[\w\s\\"]+(?<!\\)"

<强> Working demo

enter image description here

修改:我注意到您更新了输入示例。对于更新的输入,您可以使用此正则表达式:

(?:\\\\"|")[\w\s\\"]+(?:\\\\"|(?<!\\)")

<强> Working demo

enter image description here

答案 2 :(得分:0)

一种模拟原子组的方法(当模式必须失败时减少回溯很有意义)

re.findall(r'"(?=((?:[^"\\]+|\\.)*))\1"', s)

demo

答案 3 :(得分:0)

("[^...]*?")(?=\s*\.\.\.|$)

你可以试试这个。

正确地查看demo.Works以提供所需的答案。

http://regex101.com/r/bJ6rZ5/4

相关问题