首页 > 解决方案 > 如何使用 XSLT 3.1“替换”功能在括号外用逗号删除另一个数字后的数字

问题描述

我用逗号找到超过两个的数字,但我的正则表达式在括号内或括号外找到数字。如何查找不在括号内的数字。

使用正则表达式

([0-9]+, ){2,}

细绳

Albemarle Paper Co. v Moody (1975) 422 US 405, 425, 95 S Ct 2362

预期结果

Albemarle Paper Co. v Moody (1975) 422 US 405, 95 S Ct 2362

特别是,我的 XML 看起来像

<root>
<p><styled-content><italic>Agarwal v Johnson </italic>(1979) 25 C3d 932, 942, overruled on *6 other grounds in <italic>White v Ultramar, Inc.</italic> (1999) 21 C4th 563</styled-content></p>
</root>

这是带有正则表达式和替换功能的 XSL 模板:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <xsl:output method="xml" indent="yes"/>

    <xsl:template match="root">
        <xsl:copy>
            <p><xsl:value-of select="replace(p/styled-content, '[0-9]+(?:, [-0-9]+)+,(?![^()]*\))', '')"/></p>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

标签: regexreplacexsd

解决方案


注意:现在,您添加了 XSD 标记,请注意您不能在XML Schema 正则表达式中使用前瞻:“特别值得注意的是完全没有像插入符号和美元、单词边界和环视这样的锚点。 ”。

XML Schema 1.1 支持xs:assertions。使用以下内容,您可以确保123, 345, 567 text匹配和(123, 345, 567) text(123, 345, 567) 123, 345, 567 text匹配:

<xs:element name="your_element">
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:assertion test="not(matches($value, '.*\([^()]*([0-9]+, ){2,}[^()]*\).*'))"/>
      <xs:assertion test="matches($value, '.*([0-9]+, ){2,}.*')"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>

下面的答案适用于其他使用前瞻的引擎:

[0-9]+(?:, [-0-9]+)+(?![^()]*\))

证明。它将找到逗号分隔的数字序列,后面没有非括号字符,直到右括号。

如果逗号必须在第二个或更多数字之后,只需添加它:

[0-9]+(?:, [-0-9]+)+,(?![^()]*\))
                    ^
                    |___ HERE

查看更新的演示


推荐阅读