gpt4 book ai didi

regex - 去替换所有字符串

转载 作者:IT王子 更新时间:2023-10-29 01:42:23 26 4
gpt4 key购买 nike

我从 golang.org website 中阅读了示例代码.本质上,代码如下所示:

re := regexp.MustCompile("a(x*)b")
fmt.Println(re.ReplaceAllString("-ab-axxb-", "T"))
fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1"))
fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1W"))
fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))

输出是这样的:

-T-T-
--xx-
---
-W-xxW-

我理解第一个输出,但我不理解其余三个。谁能给我解释一下结果 2,3 和 4。谢谢。

最佳答案

最有趣的是 fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1W"))线。 docs say :

Inside repl, $ signs are interpreted as in Expand

Expand说:

In the template, a variable is denoted by a substring of the form $name or ${name}, where name is a non-empty sequence of letters, digits, and underscores.A reference to an out of range or unmatched index or a name that is not present in the regular expression is replaced with an empty slice.

In the $name form, name is taken to be as long as possible: $1x is equivalent to ${1x}, not ${1}x, and, $10 is equivalent to ${10}, not ${1}0.

因此,在第 3 次替换中,$1W被视为 ${1W}由于该组未初始化,因此使用空字符串进行替换。

当我说“该组未初始化”时,我的意思是说该组未在正则表达式模式中定义,因此在匹配 操作期间未填充该组。 替换 表示获取所有匹配项,然后将它们替换为替换模式。 反向引用($xx 构造)在匹配 阶段填充。 $1W模式中缺少组,因此在匹配期间未填充它,并且在发生替换阶段时仅使用空字符串。

第二个和第四个替换很容易理解,在上面的答案中已经描述过了。就$1反向引用第一个捕获组捕获的字符(用一对未转义的括号括起来的子模式),与示例 4 相同。

可以想到{}作为一种消除替换模式歧义的方法。

现在,如果您需要使结果一致,请使用命名捕获 (?P<1W>....) :

re := regexp.MustCompile("a(?P<1W>x*)b")  // <= See here, pattern updated
fmt.Println(re.ReplaceAllString("-ab-axxb-", "T"))
fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1"))
fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1W"))
fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))

结果:

-T-T-
--xx-
--xx-
-W-xxW-

自命名组 1W 以来,第二行和第三行现在产生一致的输出也是第一个组,$1编号的反向引用指向使用命名捕获捕获的相同文本 $1W .

关于regex - 去替换所有字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34673039/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com