How check string starts with number, period(.) and space in XSLT

Viewed 359

I want to check string starts with number, period(.) and space. For doing that I used regex but that not gives the correct answer.

Input:

<para>
    <text>1. this a paragaraph1</text>
    <text>12. this a paragaraph2</text>
    <text>this a paragaraph3</text>
</para>

Output should be:

<result>
    <para type="number">1. this a paragaraph1</para>
    <para type="number">12. this a paragaraph2</para>
    <para type="not number">this a paragaraph3</para>
</result>

Explanation of the logic:

You can see para/text has a string. Some of them are starting with numbers (1. , 12. ) then . and space. At that time para/@type must be number. You can see the 1st and 2nd <text> elements pass that condition. Then that @type must be number. other wise not number. just like 3rd <text> element

Tried code:

<xsl:template match="text">
    <xsl:choose>
        <xsl:when test="matches(.,'[[0-9]+]')">
            <para type="number">
                <xsl:value-of select="."/>
            </para>
        </xsl:when>
        <xsl:otherwise>
            <para type="not number">
                <xsl:value-of select="."/>
            </para>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
    
<xsl:template match="para">
    <xsl:apply-templates/>
</xsl:template>
1 Answers

Anchor the regular expression at the start of the string with ^ and use a simpler syntax e.g.

<xsl:template match="text[matches(., '^[0-9]+')]">
  <para type="number">
    <xsl:apply-templates/>
  </para>
</xsl:template>
Related