XSLT - 正则表达式替换字符

4

我有一个类似这样的示例xsl:

<doc>
  <para>text . . .text</para>
  <para>text . . .text. . . . . .text</para>
</doc>

正如您所看到的,xml 中存在一些模式,如 . . . 我需要替换点之间存在的空格为 *。因此输出应该像这样,

<doc>
  <para>text .*.*.text</para>
  <para>text .*.*.text.*.*.*.*.*.text</para>
</doc>

我已经为此编写了以下XSLT:

<xsl:template match="text()">
        <xsl:analyze-string select="." regex="(\.)(&#x0020;)(\.)">
            <xsl:matching-substring>
                <xsl:value-of select="replace(.,regex-group(2),'*')"/>
            </xsl:matching-substring>
            <xsl:non-matching-substring>
                <xsl:value-of select="."/>
            </xsl:non-matching-substring>
        </xsl:analyze-string>
    </xsl:template>

但它会消除其他所有空格,并给出以下结果,
<doc>
  <para>text .*. .text</para>
  <para>text .*. .text.*. .*. .*.text</para>
</doc>

我该如何修改XSLT以获得正确的输出...
1个回答

3

我认为

<xsl:template match="text()">
    <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>
</xsl:template>

这项工作可以完成。如LukStorms所指出的,这可以简化为

<xsl:template match="text()">
    <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>
</xsl:template>

不错。 :) 我认为正则表达式可以简化为 "\.( \.)+" - LukStorms
@LukStorms,你是对的,我已经加入了你的建议。 - Martin Honnen
我假设那些是省略号,最少必须有三个点。(.)( )(.)( .)* 变成 (.)( )(.)( .)+ 是可以的。<para>text . .text</para> 不应该有*出现在其中。 - Rudramuni TP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接