2017-08-16 99 views
1

对于正则表达式我相当缺乏经验,但我需要一个匹配函数的参数。该函数将在字符串中出现多次,并且我想返回所有参数的列表。函数参数的正则表达式

正则表达式必须匹配:

  1. 字母数字和下划线
  2. 里面直接引用在括号内
  3. 特定的函数名

这里后是一个例子字符串:

Generic3(p, [Generic3(g, [Atom('_xyx'), Atom('y'), Atom('z_')]), Atom('x_1'), Generic2(f, [Atom('x'), Atom('y')])]) 

,我想这是输出:

['_xyx', 'y', 'z_', x_1', 'x', 'y'] 

我到目前为止有:

(?<=Atom\(')[\w|_]* 

我与调用此:

进口重新

s = "Generic3(p, [Generic3(g, [Atom('x'), Atom('y'), Atom('z')]), Atom('x'), Generic2(f, [Atom('x'), Atom('y')])])" 
print(re.match(r"(?<=Atom\(')[\w|_]*", s)) 

但这只是打印None。我觉得我快到了,但是我错过了一些东西,也许在Python方面实际上会返回匹配。

+0

也许' re.findall(r“(?<= Atom \(')\ w +”,s)'?或用['r“Atom \('(\ w +)”'](https://ideone.com/BkY7SD )。 –

+0

比赛还是搜索? https://stackoverflow.com/questions/180986/what-is-the-difference-between-pythons-re-search-and-re-match – doctorlove

回答

1

你的正则表达式是接近,你需要添加\W字符找到下划线:

s = "Generic3(p, [Generic3(g, [Atom('_xyx'), Atom('y'), Atom('z_')]), Atom('x_1'), Generic2(f, [Atom('x'), Atom('y')])])" 

r = "(?<=Atom\()\W\w+" 

final_data = re.findall(r, s) 

你也可以试试这个:

import re 

s = "Generic3(p, [Generic3(g, [Atom('_xyx'), Atom('y'), Atom('z_')]), Atom('x_1'), Generic2(f, [Atom('x'), Atom('y')])])" 

new_data = re.findall("Atom\('(.*?)'\)", s) 

输出:

['_xyx', 'y', 'z_', 'x_1', 'x', 'y'] 
+0

你可以使用''Atom \('(。*?)'\ )“'并且不需要后处理正则表达式匹配。 –

+0

@WiktorStribiżew感谢您的建议。请参阅我最近的编辑。 – Ajax1234