XQuery - 如何在第二次出现字符之前提取子字符串?

XQuery - How do I extract a substring before the second occurrence of a character?

假设我有这个字符串:“123_12345_123456”

我想提取第二个“_”(下划线)之前的所有内容

我试过了:

fn:tokenize("123_1234_12345", '_')[position() le 2]

那个returns:

123
1234

其实我想要的是:

123_1234

如何实现?

我正在使用 XQuery 1.0

正则表达式灵活紧凑:

replace('123_1234_12345', '_[^_]+$', '')

另一个可能更易读的解决方案是 a) 标记字符串,b) 保留您想要保留的标记,c) 再次加入它们:

string-join(
  tokenize('123_1234_12345', '_')[position() = 1 to 2],
  '_'
)

从 Michael Kay 的已删除答案中获取基本思想,可以这样实现:

substring($input, 1, index-of(string-to-codepoints($input), 95)[2] - 1)