kkot
kkot

Reputation: 477

XSLT regex doesn't match even when in online regex tests match correctly

Given example path C:\example\innerExample\file.txt, I want to extract filename with extension using this regex, you can see it here.

<xsl:analyze-string select="$filePath" regex="$regexPattern" flags="mis">
  <xsl:matching-substring>
    <xsl:value-of select="concat(regex-group(2), regex-group(3))"/>
  </xsl:matching-substring>
</xsl:analyze-string>

This is my xslt code, is there anything I'm missing?

Upvotes: 0

Views: 124

Answers (2)

Martin Honnen
Martin Honnen

Reputation: 167506

You haven't shown us a complete but minimal examples with the proper values but with the correction of not escaping the / in the square brackets I think your pattern works with XSLT/XPath 2 and later:

Input

<root>
    <data>C:\example\innerExample\file.txt</data>
</root>

is at https://xsltfiddle.liberty-development.net/jyRYYhM transformed with

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:param name="regexPattern" as="xs:string">^(.*)[/|\\](.*)(\..*)</xsl:param>

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:template match="data">
      <xsl:copy>
          <xsl:analyze-string select="." regex="{$regexPattern}" flags="mis">
              <xsl:matching-substring>
                <xsl:value-of select="concat(regex-group(2), regex-group(3))"/>
              </xsl:matching-substring>
          </xsl:analyze-string>
      </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

into

<root>
    <data>file.txt</data>
</root>

(I have used XSLT 3 there but I think there has been no change between XSLT 2 and 3 in terms of xsl:analyze-string).

Upvotes: 1

michael.hor257k
michael.hor257k

Reputation: 116992

Without going into your attempt (which I cannot reproduce), I believe you can extract the filename with extension simply by using:

<xsl:value-of select="tokenize($filepath, '\\')[last()]"/>

Demo: http://xsltransform.hikmatu.com/6qVRKvN

Upvotes: 1

Related Questions