2017-08-16 98 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