如何使用正则表达式在XSLT中检查XML文本节点是否包含中文字符

4
在这个网站http://gskinner.com/RegExr/(一个正则表达式测试网站)上,以下正则表达式匹配成功: 匹配: [^\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>

萨克森9给我以下错误输出:
    FORX0002: Error at character 3 in regular expression "[^\x00-\xff]": invalid escape sequence
  Failed to compile stylesheet. 1 error detected.

如何在XSLT 2.0中检查中文字符?

也许可以尝试使用字符引用,而不是 &#x00;-&#xFF; - Kerrek SB
2个回答

3

在Michael Kay的帮助下,我自己回答了我的问题。谢谢Michael!

如果在给定的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>

3
XPath支持的正则表达式方言基于XSD中定义的方言:您可以在W3C文档中找到完整的规范,或者如果您喜欢更易读的内容,则可以在我的XSLT 2.0程序员参考手册中找到。不要假设所有正则表达式方言都是相同的。XPath正则表达式中没有\x转义,因为它被设计用于嵌入在已经提供&#xHHHH;的XML中。
与其使用十六进制范围,您可能会发现使用命名的Unicode块更方便,例如\p{IsCJKUnifiedIdeographs}
另请参见Unicode中汉字的完整范围是什么?

谢谢你的提示!有了你的帮助,我可以自己解决问题 :-) 我会在下面发布答案。Unicode 似乎并不是世界上最容易的事情。 - therealmarv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接