Dan McCreary
Dan McCreary

Reputation: 411

How do I replace one or more whitespace characters using the replace() function in XQuery?

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

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

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

Martin Ender
Martin Ender

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

Related Questions