Can I use a Regex in an XPath expression?
As other answers have noted, XPath 1.0 does not support regular expressions.
Nonetheless, you have the following options:
- Use an XPath 1.0 expression (note the
starts-with()
andtranslate()
functions) like this:
.//div [starts-with(@id, 'foo') and 'foo' = translate(@id, '0123456789', '') and string-length(@id) > 3 ]
Use EXSLT.NET -- there is a way to use its functions directly in XPath expressions without having to use XSLT. The EXSLT extension functions that allow RegEx-es to be used are:
regexp:match()
,regexp:replace()
andregexp:test()
Use XPath 2.0/XSLT 2.0 and its inbuilt support for regular expressions (the functions matches(), replace() and tokenize())
XPath 2.0 has some functions which support regular expressions: matches()
, replace()
, tokenize()
.
In XPath 1.0 there is no regex support.
For .NET you can use the XPath engine in Saxon.Net to have XPath 2.0 support.
So, if using the XPath 2.0 engine in Saxon.NET, your example would turn to: .//div[matches(@id,'foo\d+')]
.