簡體   English   中英

Python:用多個字符分割字符串

[英]Python : splitting string with multiple characters

我有以下輸入:

"auth-server $na me$ $1n ame$ [position [$pr io$]] xxxx [match-fqdn [[$fq dn$] [all]]]"

我需要將它們存儲在以$<>為分隔符的列表中。

預期產量:

['auth-server', '$na me$', '$1n ame$', '[position', '[$pr io$]]', 'xxxx', '[match-fqdn', '[[$fq dn$]', '[all]]]']

我怎樣才能做到這一點?

您可以做的是在空格上分割它,然后遍歷每個子字符串並檢查它是否以特殊分隔符之一開頭。 如果是這樣,請開始一個新的字符串並追加后續的字符串,直到到達結束定界符為止。 然后刪除這些子字符串,並用新的替換。

我想你想要的是

import re
re.split(r"(?<=\]) | (?=\$|\[)", "auth-server $na me$ $1n ame$ [position [$pr io$]] xxxx [match-fqdn [[$fq dn$] [all]]]")

這產生

['auth-server', '$na me$', '$1n ame$', '[position', '[$pr io$]]', 'xxxx', '[match-fqdn', '[[$fq dn$]', '[all]]]']

但是請注意,這與您描述的不完全相同,但是與您的示例相符。 似乎您想在空格前加[ ]$[

嘗試re.split和正則表達式使某人哭泣

import re
print re.split(r'(\$[^\$]+\$|\[\S+([^\]]+\]\])?|[-0-9a-zA-Z]+)',"auth-server $na me$ $1n ame$ [position [$pr io$]] xxxx [match-fqdn [[$fq dn$] [all]]]")

考慮使用pyparsing

from pyparsing import *
enclosed = Forward()
nestedBrackets = nestedExpr('[', ']') 
enclosed << ( Combine(Group(Optional('$') + Word(alphas) + Optional('$'))) | nestedBrackets )
print enclosed.parseString(data).asList()

輸出:

[['auth-server', '$na', 'me$', '$1n', 'ame$', ['position', ['$pr', 'io$']], 'xxxx', 
 ['match-fqdn', [['$fq', 'dn$'], ['all']]]]]

答案還不是很完整,但是我使用了正則regexp搜索...

a = "auth-server $na me$ $1n ame$ [position [$pr io$]] xxxx [match-fqdn [[$fq dn$] [all]]]"
m = re.search('\$.*\$', a)

將其與a.split()結合起來,我們可以進行數學運算...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM