XQuery - perform replace/match operation on string

Viewed 51

I have a string, say, let $baseString := "stringToReplace-Rem-aining-String". I want to run a conditional test to check if $baseString contains "stringToReplace" and "-", if (fn:substring($baseString,1,15) = 'stringToReplace' and fn:matches($baseString, "(([-])+)")), and if it does, I want to replace 'stringToReplace' with 'replacedString' and also "-" with "" (blank), so, output string should be replacedStringRemainingString. How can I achieve this in xQuery?

So far, I have got below 2 separate code block working - but I need to somehow combine the 2 together. And I don't really see the reason why I am using a for loop here, but this is the way I got this code block to execute without error.

let $baseString := "stringToReplace-Rem-aining-String"
for $x in $baseString return
if (fn:substring($baseString,1,15) = 'stringToReplace' and fn:matches($baseString, "(([-])+)")) 
then (fn:concat('replacedString',fn:substring($baseString,16,40))) 
 else ($baseString) 

this gives result of replacedString-Rem-aining-String and

let $baseString := "stringToReplace-Rem-aining-String"
for $x in $baseString return
if (fn:substring($baseString,1,15) = 'stringToReplace' and fn:matches($baseString, "(([-])+)")) 
then (fn:replace($baseString, "(([-])+)", ""))
 else ($baseString)

this gives result of stringToReplaceRemainingString .

Any ideas please?

2 Answers

You can try combining the thens to

then (
  let $tmp := fn:concat('replacedString',fn:substring($baseString,16,40))
  return fn:replace($tmp, "(([-])+)", "") 
) 

This gets your expected output at least for the string in your question.

Try:

let $baseString := 'stringToReplace-Rem-aining-String'
return
if (matches($baseString, '^stringToReplace.*-'))  
then ('replacedString' || translate(substring($baseString, 16), '-', ''))
else $baseString 
Related