【发布时间】:2018-05-06 06:47:42
【问题描述】:
我有一些文本,人们使用大写字母和中间的空格来突出子字符串。我想替换这些子字符串之间的空格。该模式的规则是:“至少 3 个连续的大写字母,每个字母之间有一个空格”。
我很好奇如何使用纯正则表达式以及 gsubfn 包来做到这一点,因为我认为这对它来说很容易,但在下面的 MWE 示例中,我崩溃并烧毁了额外的信被放在那里(我很好奇为什么会这样)。
MWE
x <- c(
'Welcome to A I: the best W O R L D!',
'Hi I R is the B O M B for sure: we A G R E E indeed.'
)
## first to show I have the right regex pattern
gsub('(([A-Z]\\s+){2,}[A-Z])', '<FOO>', x)
## [1] "Welcome to A I: the best <FOO>!"
## [2] "Hi I R is the <FOO> for sure: we <FOO> indeed."
library(gsubfn)
spacrm1 <- function(string) {gsub('\\s+', '', string)}
gsubfn('(([A-Z]\\s+){2,}[A-Z])', spacrm1, x)
## Error in (function (string) : unused argument ("L ")
## "Would love to understand why this error is happening"
spacrm2 <- function(...) {gsub('\\s+', '', paste(..., collapse = ''))}
gsubfn('(([A-Z]\\s+){2,}[A-Z])', spacrm2, x)
## [1] "Welcome to A I: the best WORLDL!"
## [2] "Hi I R is the BOMBM for sure: we AGREEE indeed."
## "Would love to understand why the extra letter is happening"
期望的输出
[1] "Welcome to A I: the best WORLD!"
[2] "Hi I R is the BOMB for sure: we AGREE indeed."
【问题讨论】:
-
正则表达式有两个捕获组,但第一个
gsubfn调用中的函数只有一个参数。每个捕获组应该有一个参数,即两个参数。试试这个看看它传递了什么:gsubfn('(([A-Z]\\s+){2,}[A-Z])', ~ print(list(...)), x) -
是的,看起来参数数量不匹配。如果您将
spacrm2与gsubfn('((?:[A-Z]\\s+){2,}[A-Z])', spacrm2, x)一起使用,则结果符合预期。 -
@WiktorStribiżew 你能给出答案吗
-
啊,我终于想起来了:要想通过整场比赛,你需要通过
backref=0参数。