正则表达式分裂

时间:2016-11-29 17:21:50

标签: python regex

我是regex的新手,因此我无法拆分以下字符串:

test_str = "./name[contains(substring(.,1,3),'some')],is-in,up,down"

该字符串由逗号分隔,但如果该组包含[],则不应使用逗号分隔。

所以结果应该是这样的:

["./name[contains(substring(.,1,3),'some')]", "is-in", "up", "down"]

我正在尝试这个正则表达式:

r"./*[a-z]+((\[.*?\])?)*,?/*"

...但是“ - ”

存在一些问题

3 个答案:

答案 0 :(得分:1)

这不是使用正则表达式的解决方案,但它仍然是:

# Create a function to get the number of "interesting commas" in the string:
f = lambda x: x.split(']')[1].count(',') if '[' in x and ']' in x else x.count(',')

# Reverse the string and split on the "interesting commas" and then reverse it back to normal:
[x[::-1] for x in test_str[::-1].split(",",f(test_str))][::-1]

应该返回:

# ["./name[contains(substring(.,1,3),'some')]", 'is-in', 'up', 'down']

我希望这会有所帮助。

答案 1 :(得分:0)

而不是使用re,我觉得你可以只使用堆栈来跟踪打开和关闭括号,并在必要时连接它们。这假设您总是拥有比开括号更多或相同数量的结束括号。以下代码是自我解释的,希望它可以帮助一点。

test_str = "./name[contains(substring(.,1,3),'some')],is-in,up,down"

result = test_str.split(',')

output = []

for token in result:
    if '[' in token:
        output.append(token)
    elif ']' in token and output:
        output[-1] += token
    else:
        output.append(token)
print output

答案 2 :(得分:0)

RegExps功能不够强大,因此我的解决方案不仅仅需要使用RegExps。

首先,我建议隔离[...] - 部分:

 w = re.split(r'(\[.*?\])', test_str)
 ts = [[t] if t.startswith('[') else t.split(',') for t in w ]

然后你进入ts[['./name'], ["[contains(substring(.,1,3),'some')]"], ['', 'is-in', 'up', 'down']] 之后列表必须加入:

reduce(lambda x, y: x+[y[0]] if y[0] and y[0].startswith('[') else x+y, ws)

产生(在这种情况下):

['./name', "[contains(substring(.,1,3),'some')]", '', 'is-in', 'up', 'down']

剩下的是:加入一些列表/删除空字符串。此解决方案应适用于大多数情况......

相关问题