如何在 XSLT 1.0 中使用正则表达式? [英] How do I use a regular expression in XSLT 1.0?
问题描述
我使用的是 XSLT 1.0.我的输入信息可能包含这些值
I am using XSLT 1.0. My input information may contain these values
<!--case 1-->
<attribute>123-00</attribute>
<!--case 2-->
<attribute>Abc-01</attribute>
<!--case 3-->
<attribute>--</attribute>
<!--case 4-->
<attribute>Z2-p01</attribute>
我想找出那些符合条件的字符串:
I want to find out those string that match the criteria:
if string has at least 1 alphabet AND has at least 1 number,
then
do X processing
else
do Y processing
在上面的示例中,对于案例 1、2、4,我应该能够进行 X
处理.对于情况 3,我应该能够进行 Y
处理.
In example above, for case 1,2,4 I should be able to do X
processing. For case 3, I should be able to do Y
processing.
我打算使用正则表达式(在 XSLT 1.0 中).
I aim to use a regular expression (in XSLT 1.0).
对于所有情况,属性可以取任何长度的任何值.
For all the cases, the attribute can take any value of any length.
我尝试使用 match
,但处理器返回错误.我尝试使用 translate
函数,但不确定使用方法是否正确.
I tried use of match
, but the processor returned an error.
I tried use of translate
function, but not sure if used the right way.
我在考虑.
if String matches [a-zA-Z0-9]*
then do X processing
else
do y processing.
如何使用 XSLT 1.0 语法实现它?
How do I implement that using XSLT 1.0 syntax?
推荐答案
这个解决方案在 XSLT 1.0 中确实有效(而且更简单,因为它没有也不需要使用双翻译方法.):
This solution really works in XSLT 1.0 (and is simpler, because it doesn't and needn't use the double-translate method.):
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:variable name="vUpper" select=
"'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
<xsl:variable name="vLower" select=
"'abcdefghijklmnopqrstuvwxyz'"/>
<xsl:variable name="vAlpha" select="concat($vUpper, $vLower)"/>
<xsl:variable name="vDigits" select=
"'0123456789'"/>
<xsl:template match="attribute">
<xsl:choose>
<xsl:when test=
"string-length() != string-length(translate(.,$vAlpha,''))
and
string-length() != string-length(translate(.,$vDigits,''))">
Processing X
</xsl:when>
<xsl:otherwise>
Processing Y
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
应用于提供的 XML 片段时 -- 生成格式良好的 XML 文档:
<t>
<!--case 1-->
<attribute>123-00</attribute>
<!--case 2-->
<attribute>Abc-01</attribute>
<!--case 3-->
<attribute>--</attribute>
<!--case 4-->
<attribute>Z2-p01</attribute>
</t>
产生想要的、正确的结果:
Processing Y
Processing X
Processing Y
Processing X
请注意:任何尝试使用像这样的真正 XSLT 1.0 处理器代码(从这个问题的另一个答案中借用)都将失败并显示错误:
Do Note: Any attempt to use with a true XSLT 1.0 processor code like this (borrowed from another answer to this question) will fail with error:
<xsl:template match=
"attribute[
translate(.,
translate(.,
concat($upper, $lower),
''),
'')
and
translate(., translate(., $digit, ''), '')]
">
因为在 XSLT 1.0 中禁止匹配模式包含变量引用.
because in XSLT 1.0 it is forbidden for a match pattern to contain a variable reference.
这篇关于如何在 XSLT 1.0 中使用正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!