Re: [xsl] check the type of the $pattern argument to a regular expression?

Subject: Re: [xsl] check the type of the $pattern argument to a regular expression?
From: "Andrew Welch" <andrew.j.welch@xxxxxxxxx>
Date: Mon, 16 Apr 2007 09:54:16 +0100
On 4/16/07, bryan rasmussen <rasmussen.bryan@xxxxxxxxx> wrote:
>
> It would make far more sense for you to test your regular expressions by
> some other means before putting them into your XSL.

I would have to disagree, the regular expression pattern can come from
a variable this means it can be dynamically constructed which means
that the way to make sure that the expression is correct is to test it
in the stylesheet before running.

The test as to whether a regular expression is validly formed or not
is not affected by the infinite number of possible regular
expressions, it is determined by if the syntax is correct for regular
expressions, since I'm not great at regular expressions I wanted to
see if anyone else had already made such a check. That it can't be
done using a regular expression is one thing, that it can't be done
with XSL-T 2.0 is incorrect, given that all one would need to check
the validity of regular expressions is a turing complete language.

This is one way to way check if a pattern is valid:


<xsl:stylesheet version="2.0"
	xmlns:regex="java.util.regex.Pattern"
	xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
	xmlns:saxon="http://saxon.sf.net/";>

<xsl:template match="/">
	<xsl:value-of select="saxon:try(regex:compile(']['), 'false')"/>
</xsl:template>

</xsl:stylesheet>

This attempts to compile the regex using Java, and catches the
PatternSyntaxException using Saxon SA's saxon:try() function.  In this
case it returns "false" because "][" is invalid.

If you don't have Saxon SA you could wrap the call in your own class
to catch the exception and return a boolean.

cheers
andrew

Current Thread