【问题标题】:Split string following a pattern using XSLT 2.0使用 XSLT 2.0 按照模式拆分字符串
【发布时间】:2015-11-27 14:39:41
【问题描述】:

我有一个需要使用 XSLT 2.0 解析的字符串

输入字符串

Hoffmann, Rüdiger (Universtiy-A, SomeCity, (SomeCountry); University-B, SomeCity, (SomeCountry)); Author, X; Author, B. (University-C, SomeCity (SomeCountry))

预期输出
Hoffmann, Rüdiger (Universtiy-A, SomeCity, (SomeCountry); University-B, SomeCity, (SomeCountry))
Author, X
Author, B. (University-C, SomeCity (SomeCountry))

结构是 - 作者姓名,后跟他的大学。但是,一位作者可以拥有两所大学。并且大学之间和两组作者之间的分隔符是相同的。 (在这种情况下是分号)。

我需要根据作者所属组的分隔符对其进行拆分,忽略从属关系之间的分号。

我相信它可以在正则表达式的帮助下完成,但我自己构建正则表达式的经验并不多。

【问题讨论】:

    标签: regex xslt-2.0 string-function


    【解决方案1】:

    只要大学列表和全国范围内的括号始终存在,您就可以匹配它们:

    <?xml version="1.0" encoding="UTF-8" ?>
    <xsl:transform
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        version="2.0"
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns:mf="http://example.com/mf"
        exclude-result-prefixes="xs mf">
    
        <xsl:output method="text"/>
        <xsl:param name="authors">Author, A. (Universtiy-A, SomeCity, (SomeCountry); University-B, SomeCity, (SomeCountry));Author, B. (University-C, SomeCity (SomeCountry))</xsl:param>
    
        <xsl:template match="/">
            <xsl:value-of select="mf:split($authors)" separator="&#10;"/>
        </xsl:template>
    
        <xsl:function name="mf:split" as="xs:string*">
            <xsl:param name="input" as="xs:string"/>
            <xsl:analyze-string select="$input" regex="[^;)]*?\([^(]*?\([^(]*?\)\)">
                <xsl:matching-substring>
                    <xsl:sequence select="."/>
                </xsl:matching-substring>
            </xsl:analyze-string>
        </xsl:function>
    </xsl:transform>
    

    【讨论】:

    • 非常感谢!我意识到,在某些情况下,作者根本就没有大学。我已将问题更新为类似于这样的输入。
    • 好的。它们仍然是我可以使用的非匹配子字符串序列的一部分。谢谢!
    • 另一种可能的情况是作者姓名可以包含包含分号的 HTML 实体。我已经相应地更新了这个问题。你能推荐一个合适的正则表达式吗?