2013-03-17 59 views
1

我在使用{{my_list |加入:「< \ BR>」}},它會作爲...Django自定義模板過濾器突出顯示文本塊中的一列

$GPGGA,062511,2816.8178,S,15322.3185,E,6,04,2.6,72.6,M,37.5,M,,*68 
$GPGGA,062512,2816.8177,S,15322.3184,E,1,04,2.6,72.6,M,37.5,M,,*62 
$GPGGA,062513,2816.8176,S,15322.3181,E,1,04,2.6,72.6,M,37.5,M,,*67 
$GPGGA,062514,2816.8176,S,15322.3180,E,1,03,2.6,72.6,M,37.5,M,,*66 
$GPGGA,062515,2816.8176,S,15322.3180,E,6,03,2.6,72.6,M,37.5,M,,*60 

我試圖使用正則表達式在第4和第5逗號插入CSS,所以我可以突出顯示該文本列,但是我無法找出表達式來做到這一點。其他方法來實現這一點也讚賞。

其他信息:

1)每行以'\ n'結尾。雖然這可以被刪除,並且HTML顯示不變,但我已經將它留在了正則表達式中,以便在需要時使用。 2)在這個例子中,字符串並不總是有一個很好的頭文件,例如'$ GPGGA',但是如果正則表達式需要的話,我可以添加一個來幫助標識該行的開頭。 3)如本例所示,列可能不是統一的字符數。是

我工作的過濾器如下

@register.filter(is_safe=True) 
def highight_start(text): 
    return re.sub('regex to find 4th comma in each line', ",<span class='my_highlight'>", text, flags=re.MULTILINE) 

@register.filter(is_safe=True) 
def highight_end(text): 
    return re.sub('regex to find 5th comma in each line', "</span>,", text, flags=re.MULTILINE) 

問候

回答

0

可以實現通過更換與包裹在你的<span>標籤值本身第五值。

正則表達式:^((?:[\w\d\.\$]+,){4})([\d\.]+)
更換:\1<span class='my_highlight'>\2</span>

解釋演示在這裏:http://regex101.com/r/cX5iA0

注:我認爲5號值將是數字和點

+0

謝謝,這讓我走了。 – Ninga 2013-03-17 18:58:48

0

感謝@ka,誰得到我的磁道上有此解決方案。我的工作過濾器使用:

expression = '^((?:[^,]+,){4})([^,]+)' 
replace = r'\g<1><span class="my_highlight">\g<2></span>' 

#[^,] also allows matching of hidden HTML tags in the text 
#To get the groups to insert back into the text and not be overwritten, they need to be referenced as indicated in 'replace'.