Reputation: 411
I need to replace multiple whitespace characters with a single dash in XQuery using the replace() function.
$input: 'abc def 123'
Desired Output: 'abc-def-123'
I tried:
replace($input, '/s*', '-')
and
replace($input, '/s.*', '-')
but these do not work. I am aware of normalize-space() but I want a more general function.
Thanks! - Dan
Upvotes: 3
Views: 3551
Reputation: 243449
Two additional solutions:
A simple XPath 1.0 expression:
translate(normalize-space($vInput), ' ', '-')
And an XPath 2.0 expression that replaces not only groups of spaces, but also groups of any punctuation or separator characters:
replace($vInput, '(\p{P}|\p{Z})+', '-')
Upvotes: 0
Reputation: 44259
You've got the slash the wrong way round:
replace($input, '\s*', '-')
Also, depending on the implementation in XQuery, this might insert a dash between every two non-space characters (as \s*
allows 0 characters, and therefore any empty match).
[EDIT: As Oliver Hallam points out in a comment, the XQuery specification actually requires that an error is raised if the pattern can lead to zero-length matches.]
Therefore, you might want/have to use +
(which means 1 or more characters) instead:
replace($input, '\s+', '-')
Btw, your other attempt (with the fixed slash) would match a single whitespace character plus anything that comes after it.
Upvotes: 5