从字符串中提取字符串匹配正则表达式

Extract string matching regex from string

我正在尝试使用 XQuery 从字符串中提取日期。

let $string := "This string has a yymmdd date like 151123 in it."
(: I need the date bit -> 151123 :)
let $regex := "[0-9]{2}[0-1][0-9][0-3][0-9]"

使用replace()tokenize() 我可以获得除匹配字符串以外的所有内容。 functx:get-matches() 函数看起来可以解决问题,但我不能使用它。

您应该匹配整个字符串,将日期分组并替换为组:

fn:replace($string, "^.*([0-9]{2}[0-1][0-9][0-3][0-9]).*$", "")

我无法测试代码,但希望您能了解一般流程。

XQuery 3.0 具有奇妙的analyze-string()功能:

xquery version "3.0";

let $string := "This string has a yymmdd date like 151123 in it."
(: I need the date bit -> 151123 :)
let $regex := "[0-9]{2}[0-1][0-9][0-3][0-9]"
return 
    analyze-string($string, $regex)

Returns:

<fn:analyze-string-result xmlns:fn="http://www.w3.org/2005/xpath-functions">
    <fn:non-match>This string has a yymmdd date like </fn:non-match>
    <fn:match>151123</fn:match>
    <fn:non-match> in it.</fn:non-match>
</fn:analyze-string-result>

因此,要获得匹配的字符串,您只需请求 analyze-string($string, $regex)//fn:match