Does HtmlAgilityPack have the ability to use regular expressions in its XPATH selector?

c# html-agility-pack regex xpath

Question

I would like to be able to create a collection of nodes where the text starts with a word and then a number. For example, given the following:

<p>FINDTHIS 1</p>
<p>FINDTHIS SOMETEXT</p>
<p>FINDTHIS 2</p>

I would like to be able to create a collection consisting of two paragraph nodes: FINDTHIS 1 and FINDTHIS 2.

One possible approach would be to create an xpath query like //p[starts-with(., 'FINDTHIS ')] and then use a regular expression to determine whether or not the next character is a number. If I wanted to obtain a list of matches that returned the above criteria, I could create a regular expression object and test the text for each member in the collection.

Is there a way to utilize a regular expression directly within the selector using HtmlAgilityPack?

Accepted Answer

No, the HTML Agility Pack does not currently support this. It supports XPath version 1 queries, which does not support regular expressions.

That said, you'll have to do as you recommended and select using the XPath expression up to the point where you want to use a regular expression, and then use the Where extension method to filter out the appropriate nodes based on an RegEx instance.


Popular Answer

It's not available out-of-the-box, but you can add this functionality easily. It's described here: HtmlAgilityPack: xpath and regex




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why