我有一些文本,人们在其中使用大写字母并在它们之间加上空格以突出子字符串。我想替换这些子字符串之间的空格。此模式的规则为:“至少有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)
。 - G. Grothendieckspacrm2
和gsubfn('((?:[A-Z]\\s+){2,}[A-Z])', spacrm2, x)
,结果就会如预期一样。 - Wiktor Stribiżewbackref=0
参数。 - Wiktor Stribiżew