使用正則表達式貪婪功能儘可能地匹配所有字符。所以.*\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
你能否解釋一下更好的預期輸出?你正在使用「組(1)」和「組(2)」還是「組(2)」? – Dacav 2015-03-25 12:56:07