2015-03-25 84 views
1

我想找到最後一組按以下正則表達式找到最後一組蟒蛇

輸入字符串

STR1 =「計算油耗,租賃或抵押金點擊text.See例子查看菜單,指向工作表,然後單擊工作表以進行您想要的計算.br_tag 2.下選擇要計算的值,單擊要計算的變量..br_tag 3.在文本中輸入已知值然後點擊Calculate..br_tag「

輸出我想

..br_tag 

STR2 =「計算油耗,租賃或抵押金點擊查看菜單,指向工作表,然後單擊工作表進行計算你want.br_tag 2.Under選擇值要計算,單擊要calculate..br_tag 3.輸入在文本框中已知值的變量,然後單擊calculate..br_tag BR_TAG」

輸出我想

..br_tag br_tag 

我嘗試使用

re.compile(r'(\w\.(.*?))$') 

但在這裏我得到輸出

t.br_tag 2.Under選擇你要計算的值,單擊您想要的 變量calculate..br_tag 3.在文本框中輸入已知值 ,然後單擊計算..br_tag br_tag

+0

你能否解釋一下更好的預期輸出?你正在使用「組(1)」和「組(2)」還是「組(2)」? – Dacav 2015-03-25 12:56:07

回答

2

使用正則表達式貪婪功能儘可能地匹配所有字符。所以.*\w\.匹配從開始到最後一個字符前面的所有字符。現在,.*\w(\..*)$將捕獲最後一個字符前面的所有字符。

>>> str1 = "Calculate fuel economy, lease, or mortgage payments Click the View menu, point to Worksheets, and then click the worksheet for the calculation you want.br_tag 2.Under Select the value you want to calculate, click the variable that you want to calculate..br_tag 3.Enter the known values in the text boxes and then click Calculate..br_tag" 
>>> str2 = "Calculate fuel economy, lease, or mortgage payments Click the View menu, point to Worksheets, and then click the worksheet for the calculation you want.br_tag 2.Under Select the value you want to calculate, click the variable that you want to calculate..br_tag 3.Enter the known values in the text boxes and then click Calculate..br_tag br_tag" 
>>> re.search(r'.*\w(\..*)$', str2).group(1) 
'..br_tag br_tag' 
>>> re.search(r'.*\w(\..*)$', str1).group(1) 
'..br_tag' 
>>> str3 = "Calculate fuel economy, lease, or mortgage payments Click the View menu, point to Worksheets, and then click the worksheet for the calculation you want.br_tag 2.Under Select the value you want to calculate, click the variable that you want to calculate..br_tag 3.Enter the known values in the text boxes and then click Calculate..br_tag .br_tag" 
>>> re.search(r'.*\w(\..*)$', str3).group(1) 
'..br_tag .br_tag' 

OR

你可以使用lookbehinds也。

>>> re.search(r'(?<=\w)\.(?:(?<!\w)\.|[^.])*$', str1).group() 
'..br_tag' 
>>> re.search(r'(?<=\w)\.(?:(?<!\w)\.|[^.])*$', str2).group() 
'..br_tag br_tag' 
>>> re.search(r'(?<=\w)\.(?:(?<!\w)\.|[^.])*$', str3).group() 
'..br_tag .br_tag' 

DEMO

+0

thanx爲您的答覆,但如果文本是「計算燃料經濟性,租賃或抵押付款單擊視圖菜單,指向工作表,然後單擊工作表您想要的計算.br_tag 2.Under選擇要計算的值,單擊要計算的變量..br_tag 3.在文本框中輸入已知值,然後單擊Calculate..br_tag .br_tag「 – 3ppps 2015-03-25 13:00:41

+0

上面的預期輸出是什麼?你想從最後兩個點取點嗎?清楚地解釋它。 – 2015-03-25 13:02:15

+0

實際上我想從最後一個字符前面是字符匹配...輸出我想要的是「..br_tag .br_tag」 – 3ppps 2015-03-25 13:02:40