Using xsl replace function with regular expression to find multiple instances

Having trouble installing Oxygen? Got a bug to report? Post it all here.
ann.jensen
Posts: 295
Joined: Wed Jun 17, 2015 10:19 am

Using xsl replace function with regular expression to find multiple instances

Post by ann.jensen »

Hi,
I am trying to write an XSL template using replace() function to escape occurrences of $ sign within a string, specifically when $ sign exists within opening and closing double brackets e.g. for following input
Here is a $ sign [[Buy $1000 or more and get $100 credit from us]]
I want
Here is a $ sign [[Buy \$1000 or more and get \$100 credit from us]]
returned.
However I don't know how many $ signs will exist within double square brackets.
The following will replace the first occurrence of $ sign within double square brackets and I want to know if there is a way of adding a grouping and multiplier to cause it to work for any number of occurrences in the input string?

Code: Select all

<xsl:variable name="escapeDollar" select="replace($originalText, '(\[\[.*?)\$(.*?\]\])', '$1\\\$$2')"/>
Any advice appreciated,
Regards,
Ann
chrispitude
Posts: 907
Joined: Thu May 02, 2019 2:32 pm

Re: Using xsl replace function with regular expression to find multiple instances

Post by chrispitude »

Hi Ann, while you might be able to come up with a clever regex with lookaheads and lookbehinds to do this, it would not be very maintainable.

I think a better solution is to use <xsl:analyze-string> to grab the content inside [[...]] constructs, then do the simple replace inside that:

Code: Select all

<xsl:analyze-string select="." regex="\[\[.*?\]\]">
  <xsl:matching-substring>
    <xsl:value-of select="replace(., '\$', '\\\$')"/>
  </xsl:matching-substring>
  <xsl:non-matching-substring>
    <xsl:value-of select="."/>
  </xsl:non-matching-substring>
</xsl:analyze-string>
ann.jensen
Posts: 295
Joined: Wed Jun 17, 2015 10:19 am

Re: Using xsl replace function with regular expression to find multiple instances

Post by ann.jensen »

Thank you so much chrispitude for your advice, it works perfectly.
I was not familiar with <xsl:analyze-string> before.
Thanks again,
Ann
Post Reply