Ponzo
Ponzo

Reputation: 23

XPATH : replace every ohter whitespace

I'd like to replace every other (odd?) space with x. The result should be:

axb axb axb axb axb

I tried something like:

replace ("a b a b a b a b" , " " , "x")[position() mod 2 = 0]

-- but with no result.

Upvotes: 2

Views: 144

Answers (1)

Jens Erat
Jens Erat

Reputation: 38732

First of all: fn:replace requires an XPath 2.0 (or XQuery) compatible query processor.

You cannot use fn:replace with an predicate like this. There is no array-like access to characters in XPath (like you're used to from eg. C). You probably could also solve this using fn:tokenize and a for-loop, but that's getting things rather complicated.

Your query did not return any result, as there is exactly one result (single element string sequence), but the predicate only returns every second.


Use a regular expression instead. This expression matches on non-space (\S) and space (\s) and replaces those patterns by a version with x in between. The star quantifier in the end is important for odd number of match groups (like in your example).

replace("a b a b a b a b" , "(\S+)\s+(\S+\s*)", "$1x$2")

Upvotes: 1

Related Questions