Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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

like image 705
Dan McCreary Avatar asked Jul 04 '26 01:07

Dan McCreary


1 Answers

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.

like image 127
Martin Ender Avatar answered Jul 06 '26 15:07

Martin Ender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!