Can I use a Regex in an XPath expression?

.NetXmlRegexXpath

.Net Problem Overview


Something like .//div[@id='foo\d+] to capture div tags with id='foo123'.

I'm using .NET, if that matters.

.Net Solutions


Solution 1 - .Net

As other answers have noted, XPath 1.0 does not support regular expressions.

Nonetheless, you have the following options:

.//div
[starts-with(@id, 'foo')
and
'foo' = translate(@id, '0123456789', '')
and
string-length(@id) > 3
]

Solution 2 - .Net

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+')].

Solution 3 - .Net

In .NET you have the ability to access your custom classes (and therefore regex if you can code it appropriately for your needs) via Extension Objects.

Tutorial here.

Solution 4 - .Net

I also wanted to do this so created my own basic xpath module.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionripper234View Question on Stackoverflow
Solution 1 - .NetDimitre NovatchevView Answer on Stackoverflow
Solution 2 - .NetCristian VatView Answer on Stackoverflow
Solution 3 - .NetannakataView Answer on Stackoverflow
Solution 4 - .NethojuView Answer on Stackoverflow