XSLT 2.0 regex replaces

I have the following XML:

<t>a_35345_0_234_345_666_888</t>

      

I would like to replace the first occurrence of the number after "_" with the fixed number 234. So the result should look like this:

<t>a_234_0_234_345_666_888</t>

      

I tried using the following but it doesn't work:

<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>

      

UPDATE

The following works for me (thanks @ Chris85). Just remove the underscore and add "?" To make it non-greedy.

<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>

      

+3


source to share


1 answer


Your regex is / greedy, .*

consumes everything up to the last occurrence of the next character.

So

(. *) _ \ D + _ (. *)

put

a_35345_0_234_345_666 _



in $1

. Then it 888

was removed and nothing got into $2

.

To make it not greedy add ?

after .*

. This means it *

stops at the first occurrence of the next character.

Functional example:

<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>

      

Here are some more docs on repetition and greed, http://www.regular-expressions.info/repeat.html .

+3


source







All Articles