如果您知道捕获组中没有出现某个字符,则可以在组之间使用替换该字符,然后在 XQuery 1 中对其进行标记。
例如:
tokenize(replace("abc1234", "(.+)(\d+)", "$1-$2"), "-")
要确保替换删除组之前/之后的所有内容:
tokenize(replace("abc1234", "^.*?(.+?)(\d+).*?$", "$1-$2"), "-")
您可以通过使用 string-join 为任何分隔符创建一个替换模式,如 "$1-$2-$3-$4" 将其推广到一个函数:
declare function local:get-matches($input, $regex, $separator, $groupcount) {
tokenize(replace($input, concat("^.*?", $regex, ".*?$"), string-join(for $i in 1 to $groupcount return concat("$", $i), $separator)), $separator, "q" )
};
local:get-matches("abc1234", "(.+?)(\d+)", "|", 2)
如果您不想自己指定分隔符,则需要一个函数来查找。每个长于输入字符串的字符串都不能出现在捕获组中,因此您始终可以使用更长的分隔符找到一个:
declare function local:get-matches($input, $regex, $separator) {
if (contains($input, $separator)) then local:get-matches($input, $regex, concat($separator, $separator))
else
let $groupcount := count(string-to-codepoints($regex)[. = 40])
return tokenize(replace($input, concat("^.*?", $regex, ".*?$"), string-join(for $i in 1 to $groupcount return concat("$", $i), $separator)), $separator, "q" )
};
declare function local:get-matches($input, $regex) {
local:get-matches($input, $regex, "|#☎")
};
local:get-matches("abc1234", "(.+?)(\d+)")