How to get only numbers from string with XPath

Attila Zobolyak picture Attila Zobolyak · Sep 7, 2011 · Viewed 9.9k times · Source

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

Answer

Dimitre Novatchev picture Dimitre Novatchev · Sep 7, 2011

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]', '')