-1

对不起,一般标题。我正在寻找一个 pythonre表达式来匹配以下正则表达式:

stringOfAlphaNumeric1 ( stringOfAnyCharacter1 , stringOfAnyCharacter2 , stringOfAnyCharacter3 )

此表达式可以重复多次,以空格分隔。例如:

stringOfAlphaNumeric1 ( stringOfAnyCharacter1 , stringOfAnyCharacter2 , stringOfAnyCharacter3 ) stringOfAlphaNumeric2 ( stringOfAnyCharacter4 , stringOfAnyCharacter5 , stringOfAnyCharacter6 )

我怎样才能得到以下对:

stringOfAlphaNumeric1 -> stringOfAnyCharacter1
stringOfAlphaNumeric1 -> stringOfAnyCharacter2
stringOfAlphaNumeric1 -> stringOfAnyCharacter3
stringOfAlphaNumeric2 -> stringOfAnyCharacter4
stringOfAlphaNumeric2 -> stringOfAnyCharacter5
stringOfAlphaNumeric2 -> stringOfAnyCharacter6
4

1 回答 1

3
import re

#if its fixed:  [  Key ( Value1 , Value2 , Value3 )  ]
regex = re.compile(r'([A-Za-z0-9]+) \( (.+?) , (.+?) , (.+?) \)')
s = "stringOfAlphaNumeric1 ( stringOfAnyCharacter1 , stringOfAnyCharacter2 , stringOfAnyCharacter3 ) stringOfAlphaNumeric2 ( stringOfAnyCharacter4 , stringOfAnyCharacter5 , stringOfAnyCharacter6 )"

d = dict((i[0], i[1:]) for i in regex.findall(s))

d 是:

{'stringOfAlphaNumeric2': ('stringOfAnyCharacter4', 'stringOfAnyCharacter5', 'stringOfAnyCharacter6'), 
'stringOfAlphaNumeric1': ('stringOfAnyCharacter1', 'stringOfAnyCharacter2', 'stringOfAnyCharacter3')}

得到对:

[(k, i) for k, v in d.items() for i in v]

产量:

[('stringOfAlphaNumeric2', 'stringOfAnyCharacter4'), 
('stringOfAlphaNumeric2', 'stringOfAnyCharacter5'), 
('stringOfAlphaNumeric2', 'stringOfAnyCharacter6'), 
('stringOfAlphaNumeric1', 'stringOfAnyCharacter1'), 
('stringOfAlphaNumeric1', 'stringOfAnyCharacter2'), 
('stringOfAlphaNumeric1', 'stringOfAnyCharacter3')]
于 2012-12-30T15:35:43.957 回答