简体   繁体   中英

Can I use a Regex in an XPath expression?

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

I'm using .NET, if that matters.

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   
   ]

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

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 .

我也想这样做,所以创建了自己的基本xpath模块

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM