在R正则表达式中,如何使正则表达式不是从目标字符串开始计算,而是只从第n个单词开始计算?
例如,假设一个人对用符号@替换字符串中的任何数字感兴趣。然后就可以使用gsub("\\d+", "@", string)了,比如:
gsub("\\d+", "@", "words before 879 then more words then 1001 again")其结果将是:
> "words before @ then more words then @ again"现在,按照这个例子,使用regex,如何才能使出现在字符串中的第四个单词开始的数字被替换?所以上面的示例将返回"words before 879 then more words then @ again",因为879是目标字符串中的第三个单词?
FWIW,我发现了很多关于提取和定位单词的问题,一些关于从开头到结尾的匹配问题,还有一些关于从第n个单词到或从第n个单词获取子字符串的问题。但是,在寻找模式时,没有人会忽略字符串的前n个单词,而不知道如何才能得到正则表达式。
发布于 2021-03-10 21:58:09
这与perl=TRUE (R中的双反斜杠)一起使用:
^\s*(?:\S+\s*){3}(*SKIP)(*FAIL)|\d+见证明。
解释
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
(?: group, but do not capture (3 times):
--------------------------------------------------------------------------------
\S+ non-whitespace (all but \n, \r, \t, \f,
and " ") (1 or more times (matching the
most amount possible))
--------------------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0
or more times (matching the most amount
possible))
--------------------------------------------------------------------------------
){3} end of grouping
--------------------------------------------------------------------------------
(*SKIP)(*FAIL) skip the match, search for next match
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
\d+ digits (0-9) (1 or more times (matching
the most amount possible))示例代码示例
gsub("^\\s*(?:\\S+\\s*){3}(*SKIP)(*FAIL)|\\d+", "@", "words before 879 then more words then 1001 again", perl=TRUE)发布于 2021-03-10 22:04:14
我们可以在proto中创建一个gsubfn函数来计数单词并替换
library(gsubfn)
gsubfn("\\w+", proto(fun = function(this, x) if(count > 3)
sub("\\d+", "@", x) else x), str1)
#[1] "words before 879 then more words then @ again"优点之一是它可以在任何字数处插入/替换,也可以在多个字数处替换,例如,假设我们只想替换4到6之间的单词。
gsubfn("\\w+", proto(fun = function(this, x) if(count %in% 4:6)
sub("\\d+", "@", x) else x), str1)或者一个更复杂的案子
gsubfn("\\w+", proto(fun = function(this, x) if(count %in% c(4:6, 12:15))
sub("\\d+", "@", x) else x), str2)
#[1] "words before 879 then @ replace not 1001 again and replace @ and @"数据
str1 <- "words before 879 then more words then 1001 again"
str2 <- "words before 879 then 50 replace not 1001 again and replace 1003 and 1005"https://stackoverflow.com/questions/66573450
复制相似问题