2013-02-28 31 views
0

我想知道是否可以在提出正則表達式時獲得一些幫助。我有一個文件,其中包含各種別名的長列表以及別名轉發給的電子郵件地址。該文件是在這樣的格式:Python - 正則表達式幫助

別名:[email protected]
別名2:[email protected]
別名3:[email protected]
alias4:[email protected]
alias5 :[email protected]

如何寫一個正則表達式來只抓住冒號(別名,別名2等)之前的部分?對不起,如果這是一個痛苦的簡單問題,我是Python的新手。提前致謝!

+4

不需要regexps。只需查看字符串方法的文檔['.split()'](http://docs.python.org/2/library/stdtypes.html#str.split)。祝你好運。 – bernie 2013-02-28 20:41:31

回答

1

我建議你使用split()對於這個問題,因爲你有一個非常明顯的分隔符。然而,這是一個正則表達式的解決方案:

lines = open(filename).readlines() 
regex = re.compile("(.*):.*@gmail\.com") 
aliases = [m.group(1) for m in map(lambda x: regex.match(x), lines) if m] 
1

這裏是一個列表理解爲它

first_parts = [ 
    line.split(':')[0] 
    for line in file("addresses.txt").readlines() 
    if ':' in line 
] 

它類似於此

first_parts = [] 
lines = file("addresses.txt").readlines() 
for lines in lines: 
    if ":" in line: 
     first = line.split(":")[0] 
     first_parts.append(first)