Link to home
Start Free TrialLog in
Avatar of Molko
Molko

asked on

XSLT - Replacing last occurance of a character in a string

Given a String such as

"01-01-01-01h abc def"

How do i replace the last occurance of '-' with a space so that my resulting String looks like

"01-01-01 01h abc def"

I am using XSLT 2.0

Thanks
Avatar of Gertone (Geert Bormans)
Gertone (Geert Bormans)
Flag of Belgium image

Maybe this will do
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">
    <xsl:variable name="str" select="'01-01-01-01h abc def'" />
        
    <xsl:template match="/">
        <xsl:value-of select="concat(string-join(tokenize($str, '-')[position() &lt; last()], '-'), ' ', tokenize($str, '-')[position() = last()])"></xsl:value-of>
    </xsl:template>
</xsl:stylesheet>

Open in new window

Avatar of Molko
Molko

ASKER

wow...thats fairly complicated

Would it be easier if last '-' was alway followed by 2 numerics and then a character ? ie. -01h

It is not that complex.

I break the string in pieces at the '-'
I bring them all together except the last
I add the space
I add the last from the breakup

pretty convinced that this is the best performing solution
if you don't like the code, stuff it away in a function like this

You could do this with a regular expression if you were certain that -\d\dh would only occur once
see code in next comment
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:pfn="#internal"
    exclude-result-prefixes="xs"
    version="2.0">
    <xsl:variable name="str" select="'01-01-01-01h abc def'" />
        
    <xsl:template match="/">
        <xsl:value-of select="pfn:replace-last-occurence-of($str, '-', ' ')"/>
    </xsl:template>
    
    <xsl:function name="pfn:replace-last-occurence-of">
        <xsl:param name="str"/>
        <xsl:param name="find"/>
        <xsl:param name="replace"/>
        <xsl:value-of select="concat(string-join(tokenize($str, $find)[position() &lt; last()], $find), $replace, tokenize($str, $find)[position() = last()])"></xsl:value-of>
    </xsl:function>
</xsl:stylesheet>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Gertone (Geert Bormans)
Gertone (Geert Bormans)
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial