我正在寻找一种方法来匹配之前匹配的部分或整个组。例如,假设我们有以下文本:
这是一个很长的文本,“带有”一些我“需要”在它们自己的上下文中匹配的引用字符串
像 (.{1,20})(".*?")(.{1,20})
这样的正则表达式给出以下输出:
# | 1st group | 2nd group | 3rd group
------------------------------------------------------------------
1 | is a very long text | "with" | some quoted strings
2 | I | "need" | to extract in their
目标是强制正则表达式从第 1 场比赛中重新匹配第 3 组的一部分 - 或者当引号字符串非常接近时的整个比赛 - 当匹配第 2 场比赛时。基本上我想要以下输出:
# | 1st group | 2nd group | 3rd group
------------------------------------------------------------------
1 | is a very long text | "with" | some quoted strings
2 | me quoted strings I | "need" | to extract in their
或许,反向引用支持可以解决问题,但 go 正则表达式引擎缺少它。
最佳答案
如果回到最初的问题,您需要提取上下文中的引号。
因为你没有前瞻性,你可以使用 regexp 来匹配引号(或者甚至只是 strings.Index),并且只获取字节范围,然后通过扩展范围来扩展以包含上下文(这可能需要更多的工作如果处理复杂的 UTF 字符串)。
类似于:
input := `this is a very long text "with" some quoted strings I "need" to extract in their own context`
re := regexp.MustCompile(`(".*?")`)
matches := re.FindAllStringIndex(input, -1)
for _, m := range matches {
s := m[0] - 20
e := m[1] + 20
if s < 0 {
s = 0
}
if e >= len(input) {
e = -1
}
fmt.Printf("%s\n", input[s:e])
}
关于regex - 重新匹配相同或部分先前匹配的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52367973/