2016-08-13 117 views
1

我的正則表達式今天很弱。我試圖將字符串中的組分成5個部分,格式爲:正則表達式分組

substring delimiter substring number(space) substring 

我試過使用字邊界但沒有成功。 。我已經訴諸使用*(貪婪和懶惰,我知道)這是比所有

這裏沒有工作更好一點就是我有:

import re 

s = "FOREVER - Alabaster Cuttlefish - 01 This Style Is Cheese" 

m = re.compile("(.*)(\s-\s)(\d{1,3}\s)(.*)") 
g = m.match(s) 
if g: 
    print m.match(s).group(1) # FOREVER 
    print m.match(s).group(2) # - 
    print m.match(s).group(3) # Alabaster Cuttlefish 
    print m.match(s).group(4) # 01 

    # fail 
    # print m.match(s).group(5) # This Style Is Cheese 

5組不存在,因爲它得到在第一組中捕獲。因此我的困惑。

回答

2

你非常接近。替換正則表達式:

m = re.compile("(.*?)(\s-\s)([^\d]*)(\d{1,3}\s)(.*)") 

如果你不想在雪花墨魚的末尾加上破折號,用途:

import re 

s = "FOREVER - Alabaster Cuttlefish - 01 This Style Is Cheese" 

m = re.compile("(.*)(\s-\s)(.*)(\s-\s)(\d{1,3}\s)(.*)") 
g = m.search(s) 
if g: 
    print g.group(1) # FOREVER 
    print g.group(2) # - 
    print g.group(3) # Alabaster Cuttlefish 
    print g.group(5) # 01 
    print g.group(6) # This Style Is Cheese