2015-06-22 45 views
3

我有下面的XML:XSLT 2.0正則表達式替換

<t>a_35345_0_234_345_666_888</t> 

我想有固定數量的234後更換號碼的第一次出現「_」所以結果應該是這樣的:

<t>a_234_0_234_345_666_888</t> 

我已經使用下列但它不能正常工作的嘗試:

<xsl:stylesheet version="2.0" 
       xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
       xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xsl:template match="/"> 
    <xsl:value-of select='replace(., "(.*)_\d+_(.*)", "$1_234_$2")'/> 
    </xsl:template> 
</xsl:stylesheet> 

UPD ATE

下對我的作品(感謝@ Chris85)。只是刪除下劃線,並添加「?使它非貪婪。

<xsl:stylesheet version="2.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xsl:template match="/"> 
    <xsl:value-of select='replace(., "(.*?)_\d+(.*)", "$1_234$2")'/> 

    </xsl:template> 
</xsl:stylesheet> 
+1

當前會發生什麼?我認爲你需要使它不貪婪。「*?'。例如'的' – chris85

+0

喜@ Chris85 - 感謝奏效!是否可以更改表達式,以便在末尾使用字邊界而不是「_」? XSLT不支持通常的字邊界(\ b)。我正在使用XSLT 2.0。謝謝你! –

+0

我不確定我經常使用XSLT(每年一次或更少)。我可以更頻繁地使用正則表達式來描述你遇到的問題,也許還有另一種方法呢? – chris85

回答

3

你的正則表達式是/是貪婪的,在.*消耗的一切,直到下一個字符的最後一次出現。

所以

(。*)_ \ d + _(。*)

是把

a_35345_0_234_345_666_

$1。然後888除去所並沒有什麼進入$2

要使它非貪婪的.*後添加?。這告訴*在第一次出現下一個字符時停止。

功能例如:

<xsl:stylesheet version="2.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xsl:template match="/"> 
    <xsl:value-of select='replace(., "(.*?)_\d+(.*)", "$1_234$2")'/> 
    </xsl:template> 
</xsl:stylesheet> 

這裏有重複和貪婪,http://www.regular-expressions.info/repeat.html一些更多的文檔。