4

在此网站http://gskinner.com/RegExr/(这是一个 RegEx 测试网站)上,此正则表达式匹配有效匹配: [^\x00-\xff]
示例文本:test123 或元件数据不可用

但如果我有这个输入 XML:

<?xml version="1.0" encoding="UTF-8" ?>
<root>
  <node>test123 或元件数据不可用</node>
</root>

我用 Saxon 9 试试这个 XSLT 2.0 样式表:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/root/node">
    <xsl:if test="matches(., '[^\x00-\xff]')">
      <xsl:text>Text has chinese characters!</xsl:text>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

Saxon 9 给了我以下错误输出:

    FORX0002: Error at character 3 in regular expression "[^\x00-\xff]": invalid escape sequence
  Failed to compile stylesheet. 1 error detected.

如何在 XSLT 2.0 中检查汉字?

4

2 回答 2

3

在 Michael Kay 的帮助下,我可以自己回答我的问题。谢谢迈克尔!该解决方案有效,但在我看来,这么长的 Unicode 范围看起来不太漂亮。

如果在给定的 XML 中使用正则表达式找到任何中文字符,此 XSLT 将打印一条文本消息:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/root/node">
    <xsl:if test="matches(.,'[&#x4E00;-&#x9FFF;&#x3400;-&#x4DFF;&#x20000;-&#x2A6DF;&#xF900;-&#xFAFF;&#x2F800;-&#x2FA1F;]')">
      <xsl:text>Text has chinese characters!</xsl:text>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

使用命名 Unicode 块的解决方案:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/root/node">
    <xsl:if test="matches(., '[\p{IsCJKUnifiedIdeographs}\p{IsCJKUnifiedIdeographsExtensionA}\p{IsCJKUnifiedIdeographsExtensionB}\p{IsCJKCompatibilityIdeographs}\p{IsCJKCompatibilityIdeographsSupplement}]')">
      <xsl:text>Text has chinese characters!</xsl:text>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>
于 2011-07-08T14:00:44.147 回答
3

XPath 支持的正则表达式方言基于 XSD 中定义的方言:您可以在 W3C 文档中找到完整的规范,或者如果您更喜欢更具可读性的内容,请在我的 XSLT 2.0 Programmer's Reference 中找到。不要假设所有的正则表达式方言都是相同的。XPath 正则表达式中没有任何\x转义,因为它是为嵌入已经提供&#xHHHH;.

与使用十六进制范围相比,您可能会发现使用命名的 Unicode 块更方便,例如\p{IsCJKUnifiedIdeographs}.

另请参阅Unicode 中汉字的完整范围是什么?

于 2011-07-07T15:15:47.627 回答