gsub 在匹配时忽略大小写但输出应遵循原始大小写

gsub ignore case on matching but output should follow original case

我想匹配 log-in 而不管其大小写,但 log-in (with ignore case) 的结果匹配应遵循其原始大小写。

txt <- 'log-in LOG-in LOG-IN LOG IN log-on LOG-on LOG-ON LOG ON 23-2'
have <- gsub(pattern = 'log[ -]in',replacement ='login' ,x = txt,ignore.case = T)
have 
> "login login login login log-on LOG-on LOG-ON LOG ON 23-2"

want
> "login LOGin LOGIN LOGIN log-on LOG-on LOG-ON LOG ON 23-2"

试试这个:

gsub(pattern = '(log)[ -](in)', replacement ='\1\2' , x = txt, ignore.case = T)
[1] "login LOGin LOGIN LOGIN log-on LOG-on LOG-ON LOG ON 23-2"

这适用于反向引用:\1以其确切形式(包括大小写)(log) 向后引用第一个捕获组 (log) 和 'remembers',而\2 指回第二个捕获组 (in)

一种方法是将 login 部分命名为一组,并在替换文本中使用“\1”和“\2”。

txt <- 'log-in LOG-in LOG-IN LOG IN log-on LOG-on LOG-ON LOG ON 23-2'
gsub("(log)[ -](in)", "\1\2", txt, ignore.case=TRUE)

或者,如果您想同时为登录和注销同时执行此操作,例如您可以在 'g'.

之后替换“-”或“”
want <- gsub(x = txt, pattern = "(?<=g)[- ]", '', perl = TRUE,ignore.case = T)

如果您只是想登录,也请提前查看。

want <- gsub(x = txt, pattern = "(?<=g)[- ](?=i)", '', perl = TRUE,ignore.case = T)