2016-01-20 32 views
1

我需要一個幫助,搞清楚,如何正確地實現正則表達式。蟒蛇 - 提到解析正則表達式

pattern = re.compile(r'\[(^[a-z0-9]*|[a-z0-9][^]]*)]') 

重點是解析'Text [123 | Foo bar] text'等語句。
人類可讀的正則表達式是 - [0-9 |任何符號]。

UPD: 預期的結果:

>>> input = 'text [1|Foo bar] text [222|Text] abc' 
>>> pattern.findall(input) 
[('1', 'Foo bar'), ('222', 'Text')] 
+3

請從您要明確提取物 - 什麼什麼文字澄清。我不明白 – SIslam

+1

請提供一個示例輸入字符串和一個期望的輸出。 –

+0

至少'|'需要轉義成'\ |'。未轉義它是替代模式運算符。 – dhke

回答

1

您可以使用

\[(\d+)\|([^][]*)] 

regex demo

正則表達式:

  • \[ - 開幕方括號
  • (\d+) - 1組匹配的一個或多個數字
  • \| - 字面|
  • ([^][]*) - Group 1 matching zero or more characters other than [and]`。
  • ] - 關閉]

Python demo

import re 
p = re.compile(r'\[(\d+)\|([^][]*)]') 
test_str = "Text [123|Foo bar] text" 
print (p.findall(test_str))