doublemc
doublemc

Reputation: 3311

Regex in XSLT transformation?

I need to extract some data from XML field using XSLT 2.0 and I don't know the best way to do that. Here is my XML value:

<PayReaCom>AP@1267347323/11122/01/2017/REF1AP@</PayReaCom>

And I need everything between AP@ and AP@; so in this case:

1267347323/11122/01/2017/REF1

I tried using substring, but I don't know how to set restrictions for AP@.

Can I use a regular expression here?

Upvotes: 0

Views: 689

Answers (3)

michael.hor257k
michael.hor257k

Reputation: 117073

In XSLT 2.0, you could do simply:

tokenize($string, 'AP@')[2]

to return the string in-between the first and the second occurrences of the AP@ delimiter.


For example, given:

<PayReaCom>alphaAP@bravoAP@charlie</PayReaCom>

the instruction:

<xsl:value-of select="tokenize(PayReaCom, 'AP@')[2]" />

will return:

bravo

Upvotes: 1

Valdi_Bo
Valdi_Bo

Reputation: 30991

Assuming that PayReaCom element is the context node, to print the required fragment, you can use:

<xsl:value-of select="substring-before(substring-after(., 'AP@'), 'AP@')"/>

First substring-after function "cuts off" the initial AP@ (and whatever was before). Then the result of this function is processed by substring-before function, which "cuts off" the second instance of AP@ (and whatever was after).

Or if you want to save this substring in a variable, use:

<xsl:variable name="yourName" .../>

with the select clause as above.

Upvotes: 2

gfullam
gfullam

Reputation: 12045

xsl:analyze-string

<xsl:analyze-string select="PayReaCom" regex="AP@(.+?)AP@">
  <xsl:matching-substring>
    <!-- Replacement here -->
  </xsl:matching-substring>
</xsl:analyze-string>

See: https://www.w3.org/TR/xslt20/#analyze-string

You may want to use this in conjunction with the function: regex-group.

See also: https://www.w3.org/TR/xslt20/#function-regex-group

Upvotes: 0

Related Questions