Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only numbers from string with XPath

I have a string which contains numbers. Is it feasible only with XPath that I get only numbers from it?

For example: myString="abcd12ef34gh567", result: 1234567

like image 633
Attila Zobolyak Avatar asked Sep 07 '11 16:09

Attila Zobolyak


People also ask

What is number in XPath?

Strings are converted to a number by stripping the leading whitespace in the string before the number and ignoring whitespace after the number. If the string does not match this pattern, then the string is converted to NaN. Boolean true is converted to 1. False is converted to 0.

Is XPath unique for each element?

Unlike ID attributes, every element in a web page has a unique XPath. An XPath (XML Path Language) is a query language for selecting nodes from XML like documents, such as HTML in our case.


2 Answers

Use:

translate(., translate(.,'0123456789',''), '')

This is the so called "double-translate" method, first proposed by @Michael Kay and can be used both in XPath 1.0 and in XPath 2.0.

Of course, in XPath 2.0 using RegeX will generally be more efficient:

replace('abc123def590xyz', '[^\d]', '')
like image 57
Dimitre Novatchev Avatar answered Sep 24 '22 04:09

Dimitre Novatchev


If you can guarantee that the non-digit characters will be only lower-case letters (like in your example), you could do the following in XPath 1:

translate($myString, 'abcdefghijklmnopqrstuvwxyz', '')

You can add other characters to the alphabet string as necessary.

In XPath 2, you could use a regex:

replace($myString, '[^0-9]', '')
like image 33
James Sulak Avatar answered Sep 26 '22 04:09

James Sulak