saxon:replace-with

Uses a regular expression to perform string replacement; substrings that match the regex are converted to their replacement strings by calling a user-supplied function.

replace-with($in as xs:string?, $regex as xs:string, $replacer as function(xs:string) as xs:string) ➔ xs:string

Arguments

 

$in

xs:string?

The input string

 

$regex

xs:string

The regular expression

 

$replacer

function(xs:string) as xs:string

User-supplied function, which is called to convert the matching substrings into their replacements

Result

xs:string

replace-with($in as xs:string?, $regex as xs:string, $replacer as function(xs:string) as xs:string, $flags as xs:string) ➔ xs:string

Arguments

 

$in

xs:string?

The input string

 

$regex

xs:string

The regular expression

 

$replacer

function(xs:string) as xs:string

User-supplied function, which is called to convert the matching substrings into their replacements

 

$flags

xs:string

Regular expression flags

Result

xs:string

Namespace

http://saxon.sf.net/

Notes on the Saxon implementation

Available since Saxon 10.

Details

This function is similar to the fn:replace function, but instead of supplying a replacement string, the caller supplies a callback function which will be invoked to calculate a replacement for each matching substring in the input.

The string returned by the callback function is inserted "as is" into the result string; "$" and "\" are not recognized as special characters.

For example:

  • replace-with("Registration: abc123", "[a-z]{3}[0-9]{3}", upper-case#1) returns "Registration: ABC123".

  • replace-with("Part 2 Chapter 5", "[0-9]+", function($in){string(number($in)+1)} returns "Part 3 Chapter 6".

  • saxon:replace-with('ALPHA_x002F_OMEGA', '_x[0-9A-F]{4}_', function($s) {$s => substring(3, 4) => bin:hex() => bin:unpack-unsigned-integer(0,2) => codepoints-to-string()})

    outputs ALPHA/OMEGA (this handles a convention sometimes used to encode special characters in XML element and attribute names). This example uses functions from the EXPath Binary module.

The regular expression must not be one that matches a zero-length string.

Note: the callback function does not have access to matching groups within the matched substring, only to the matched substring as a whole.