How to get only numbers from string with XPath
Asked Answered
H

2

12

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

Handcraft answered 7/9, 2011 at 16:11 Comment(0)
S
17

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]', '')
Sprit answered 7/9, 2011 at 17:35 Comment(1)
+1, "double-translate" very skilful solution. Regex improvement: \DIncurious
G
2

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]', '')
Gorge answered 7/9, 2011 at 16:16 Comment(1)
@_James_Sulak: It isn't necessary to know in advance the set of non-numeric characters -- see my answer.Sprit

© 2022 - 2024 — McMap. All rights reserved.