2010-05-27 220 views
0

我試圖從正則表達式的字符串中提取/匹配數據,但我似乎沒有得到它。將某些字符匹配到一個字符串中的Python

我wan't從以下字符串中提取的I386(最後之間的文本 - 和.ISO):

/xubuntu/daily/current/lucid-alternate-amd64.iso 

/xubuntu/daily/current/lucid-alternate-i386.iso 

這也應該在的情況下工作給出的結果應該是i386或amd64。

非常感謝您的幫助。

回答

1

如果您將使用re.compile()匹配其中幾個這些行並保存生成的正則表達式對象以供重用is more efficient

s1 = "/xubuntu/daily/current/lucid-alternate-i386.iso" 
s2 = "/xubuntu/daily/current/lucid-alternate-amd64.iso" 

pattern = re.compile(r'^.+-(.+)\..+$') 

m = pattern.match(s1) 
m.group(1) 
'i386' 

m = pattern.match(s2) 
m.group(1) 
'amd64' 
+0

你不需要regexs for this http://stackoverflow.com/questions/2925306/python-matching-some-characters-into-a-string/2925399#2925399 – jfs 2010-05-27 22:46:28

+0

我知道,但它被標記爲Python和正則表達式 – 2010-05-27 23:03:31

1
r"/([^-]*)\.iso/" 

您想要的位將在第一個捕獲組中。

+0

謝謝!但是不起作用:( – user175259 2010-05-27 22:13:13

+0

你試圖使用'match()'還是'search()'?因爲這是一種部分匹配模式,所以它應該與'search()'而不是'match()'一起使用。 (因爲'match()'試圖匹配整個字符串,而不僅僅是一部分) – Amber 2010-05-27 22:30:16

1

首先,讓我們的生活變得更簡單,只獲取文件名。

>>> os.path.split("/xubuntu/daily/current/lucid-alternate-i386.iso") 
('/xubuntu/daily/current', 'lucid-alternate-i386.iso') 

現在只需抓住最後一個短劃線和'.iso'之間的所有字母。

+0

我仍然面臨無法獲取所需文本的問題:((我從來沒有用過正則表達式) – user175259 2010-05-27 22:15:20

3

你也可以在此情況下(而不是正則表達式)使用split

>>> str = "/xubuntu/daily/current/lucid-alternate-i386.iso" 
>>> str.split(".iso")[0].split("-")[-1] 
'i386' 

split就可以瞭解有關您的字符串得到了「分裂」元素的列表。然後使用Python的slicing syntax可以找到適當的部分。

+0

真棒!!'謝謝。 – user175259 2010-05-27 22:25:50

+0

'str.rsplit('.iso',1)[0] .rsplit(' - ',1)[ - 1]' – jfs 2010-05-27 22:44:44

+0

'str.rpartition('.iso')[0]。 rpartition(' - ')[ - 1]' – jfs 2010-05-27 22:45:17

0

該表達式應該沒有前導斜線。

import re 

line = '/xubuntu/daily/current/lucid-alternate-i386.iso' 
rex = re.compile(r"([^-]*)\.iso") 
m = rex.search(line) 
print m.group(1) 

產生 'I386'

0
reobj = re.compile(r"(\w+)\.iso$") 
match = reobj.search(subject) 
if match: 
    result = match.group(1) 
else: 
    result = "" 

主題包含文件名和路徑。

0
>>> import os 
>>> path = "/xubuntu/daily/current/lucid-alternate-i386.iso" 
>>> file, ext = os.path.splitext(os.path.split(path)[1]) 
>>> processor = file[file.rfind("-") + 1:] 
>>> processor 
'i386' 
相關問題