如何 select 字符串中的整数和小数(XSLT、XPath)

How to select integer and decimal numbers from a string (XSLT, XPath)

我在 XSLT 中有一个函数,它从字符串中获取整数。

Blockquote Ex: Input: income 200 addback 600 Output: 200 600.

我要更改函数以显示字符串中的第一个整数或小数:

Blockquote Ex: Input: income 200.20 addback 12.4 Output: 200.20

现在显示:

Output: 200 20 12 4

为了达到预期的结果,我需要更改功能中的哪些内容?

<xsl:function name="fn:trimNumber" as="xs:integer*">
    <xsl:param name="pStr"/>
        <xsl:sequence select=
            "for $i in tokenize($pStr, '[^0-9]+')[.]
            return xs:integer($i)"/>
</xsl:function>

我。在您的函数中,评估此 XPath 2.0 表达式:(您需要用函数声明中使用的参数名称替换 replace() 的第一个参数,现在是 . -- 例如 $pText):

replace(., '^(([\.-]?[^\d\.-])+)?([+-]?\d*\.?\d+).*$', '')

这是一个完整的例子:

XML 文档:

<t>
   <line>income great. 13 addback 12.4 xxxx 1.23</line>
   <line>income great. 3.14 addback 12.4 xxxx 1.23</line>
   <line>income great. .55 addback 12.4 xxxx 1.23</line>
   <line>income great. -13 addback 12.4 xxxx 1.23</line>
   <line>income great. -3.14 addback 12.4 xxxx 1.23</line>
   <line>income great. -.55 addback 12.4 xxxx 1.23</line>
</t>

XSLT 转换 -- 只需要输出上面 XPath 表达式的计算结果:

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

  <xsl:template match="/*/*">
    <xsl:value-of select="replace(., '^(([\.-]?[^\d\.-])+)?([+-]?\d*\.?\d+).*$', '')"/>
  </xsl:template>
</xsl:stylesheet>

将此转换应用于上述 XML 文档时,会生成所需的正确结果:

   13
   3.14
   .55
   -13
   -3.14
   -.55

二. 如果可以使用 XPath 3.0,请使用标准的 XPath 3.0 函数:

analyze-string()