“Regular expression”-style replace in XSLT 1.0

断了今生、忘了曾经 提交于 2019-12-03 16:41:55

I'm hoping you haven't simplified the problem too much for asking it on SO, because this shouldn't be that much of a problem.

You can define a template and recursively call it as long as you keep the input string's format consistent.

For example,

<xsl:template name="TrimMulti">
  <xsl:param name="InputString"/>
  <xsl:variable name="RemainingString" 
    select="substring-after($InputString,';#')"/>
  <xsl:choose>
    <xsl:when test="contains($RemainingString,';#')">
      <xsl:value-of 
        select="substring-before($RemainingString,';#')"/>
      <xsl:text>, </xsl:text>
      <xsl:call-template name="TrimMulti">
        <xsl:with-param 
          name="InputString"
          select="substring-after($RemainingString,';#')"/>
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$RemainingString"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

I tested this template out with the following call:

<xsl:template match="/">
  <xsl:call-template name="TrimMulti">
    <xsl:with-param name="InputString">19;#John Smith;#17;#Ben Reynolds;#1;#Terry Jackson</xsl:with-param>
  </xsl:call-template>
</xsl:template>

And got the following output:

John Smith, Ben Reynolds, Terry Jackson

Which seems to be what you're after.

The explanation of what it is doing is easy to explain if you're familiar with functional programming. The InputString parameter is always in the form [number];#[name];#[rest of string]. Each call of the TrimMulti template chops off the [number];# part and prints off the [name] part, then passes the remaining expression to itself recursively.

The base case is when InputString is in the form [number];#[name], in which case the RemainingString variable won't contain ;#. Since we know this is the end of the input, we don't output a comma this time.

If the ';' and '#' characters are not valid in the input because they are delimiters then why wouldn't the translate function work? It might be ugly (you have to specify all valid characters in the second argument and repeat them in the third argument) but it would be easier to debug.

translate($InputString, ';#abcdefghijklmnopqrstuvABCDEFGHIJKLMNOPQRSTUZ0123456789,- ', ', abcdefghijklmnopqrstuvABCDEFGHIJKLMNOPQRSTUZ0123456789,- ')
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!