gpt4 book ai didi

xslt xsl :analyze-string and regex expression

转载 作者:行者123 更新时间:2023-12-05 00:38:28 25 4
gpt4 key购买 nike

我有一个 xml 文件,我必须在其中找到模式并在匹配的特定模式周围放置一个 "标记。

<xml>
<foo>
<id>1</id>
<description>This is section 1, this is section 1 or 2, this is section 1 and 2</description>
</foo>
</xml>

现在在文件中,我必须找到一个模式“section 1”、“section 1 or 2”和“section 1 and 2”,并在匹配的词周围放置一个“标记。

我写了一个这样的xslt:

  <xsl:template match="text()">

<xsl:analyze-string select="." regex="section\s\d+|section\s\d+\s+or\s+\d|section\s\d+\s+and\s+\d">
<xsl:matching-substring>
<xsl:if test="matches(.,'section\s\d+')" >
<xsl:text>"</xsl:text>
<xsl:value-of select="."/>
<xsl:text>"</xsl:text>
</xsl:if>
<xsl:if test="matches(.,'section\s\d+\s+or\s+\d')" >
<xsl:text>"</xsl:text>
<xsl:value-of select="."/>
<xsl:text>"</xsl:text>
</xsl:if>
<xsl:if test="matches(.,'section\s\d+\s+and\s+\d')" >
<xsl:text>"</xsl:text>
<xsl:value-of select="."/>
<xsl:text>"</xsl:text>
</xsl:if>
</xsl:matching-substring>
<xsl:non-matching-substring>
<xsl:value-of select="current()"/>
</xsl:non-matching-substring>
</xsl:analyze-string>
</xsl:template>

我在这里面临的问题是模式“第 1 部分”也匹配所有其他模式,所以我没有得到想要的结果

以上转换结果为

<xml>
<foo>
<id>1</id>
<description>This is "section 1", this is "section 1" or 2, this is "section 1" and 2</description>
</foo>
</xml>

我想要这个输出的地方。

<xml>
<foo>
<id>1</id>
<description>This is "section 1", this is "section 1 or 2", this is "section 1 and 2"</description>
</foo>
</xml>

关于如何实现它的任何想法......并获得期望的结果。

谢谢。

最佳答案

这似乎适用于您的输入:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>

<xsl:template match="text()">
<xsl:analyze-string select="." regex="section\s+\d+(\s+(or|and)\s+\d+)?">
<xsl:matching-substring>
<xsl:text>"</xsl:text>
<xsl:value-of select="."/>
<xsl:text>"</xsl:text>
</xsl:matching-substring>
<xsl:non-matching-substring>
<xsl:value-of select="current()"/>
</xsl:non-matching-substring>
</xsl:analyze-string>
</xsl:template>

</xsl:stylesheet>

尽管如果您只是生成一个字符串而不是元素,xsl:anayze-string 会超出您的需要,并且会产生相同的结果:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>

<xsl:template match="text()">
<xsl:value-of select="replace(.,'section\s+\d+(\s+(or|and)\s+\d+)?','&quot;$0&quot;')"/>
</xsl:template>

</xsl:stylesheet>

关于xslt xsl :analyze-string and regex expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9931243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com