我正在使用正则表达式来替换一些子字符串。替换值重复使用部分匹配项。我想不区分大小写地匹配,但在替换中,我想要匹配的东西的小写版本。
library(stringi)
x <- "CatCATdog"
rx <- "(?i)(cat)(?-i)"
stri_replace_all_regex(x, rx, "{$1}")
# [1] "{Cat}{CAT}dog"
这与我想要的很接近,除了“cat”应该小写。也就是说,输出字符串应该是 "{cat}{cat}dog"
。
下面的代码不起作用,但它表明了我的意图。
stri_replace_all_regex(x, rx, "{tolower($1)}")
以下技术确实有效,但它很丑陋,不是很普遍,也不是很有效。我的想法是用匹配我想要的但不是替换值的正则表达式替换正则表达式(即“cat”而不是“{cat}”)。然后在每个输入字符串中搜索第一个匹配项,找到匹配项的位置,做一个子串替换,然后寻找下一个匹配项,直到没有为止。太可怕了。
x <- "CatCATdog"
rx <- "(?i)((?<!\\{)cat(?!\\}))(?-i)"
repeat{
detected <- stri_detect_regex(x, rx)
if(!any(detected))
{
break
}
index <- stri_locate_first_regex(x[detected], rx)
match <- tolower(stri_match_first_regex(x[detected], rx)[, 2])
stri_sub(x[detected], index[, 1], index[, 2]) <- paste0("{", match[detected], "}")
}
我觉得一定有更好的方法。
如何用小写值替换不区分大小写的匹配项?
感谢评论的启发,我发现我要找的东西是“replacement text case conversion”。
最佳答案
如果您需要执行任何类型的字符串操作,您可以使用 gsubfn
:
> library(gsubfn)
> rx <- "(?i)cat"
> s = "CatCATdog"
> gsubfn(rx, ~ paste0("{",tolower(x),"}"), s, backref=0)
[1] "{cat}{cat}dog"
您可以像在 JavaScript 中的 String#replace
中使用匿名回调方法一样使用 gsubfn
(您可以使用 function 指定捕获组的参数(args)
,并在内部进行更复杂的操作)。
关于regex - 不区分大小写地匹配正则表达式,用特定的大小写替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39449416/