【发布时间】:2016-05-19 12:59:42
【问题描述】:
我在 R 中使用 gsub 将文本添加到字符串的中间。它运行良好,但由于某种原因,当位置过长时会引发错误。代码如下:
gsub(paste0('^(.{', as.integer(loc[1])-1, '})(.+)$'), new_cols, sql)
Error in gsub(paste0("^(.{273})(.+)$"), new_cols, sql) : invalid regular expression '^(.{273})(.+)$', reason 'Invalid contents of {}'
当括号中的数字(在本例中为 273)较少时,此代码可以正常工作,但当它很大时则不行。
这会产生错误:
sql <- "The cat with the bat went to town. He ate the fat mat and wouldn't stop til the sun came up. He was a fat cat that lived with a rat who owned many hats.The cat with the bat went to town. He ate the fat mat and wouldn't stop til the sun came up. He was a fat cat that lived with a rat who owned many hats."
new_cols <- "happy"
gsub('^(.{125})(.+)$', new_cols, sql) #**Works
gsub('^(.{273})(.+)$', new_cols, sql)
Error in gsub("^(.{273})(.+)$", new_cols, sql) : invalid regular expression '^(.{273})(.+)$', reason 'Invalid contents of {}'
【问题讨论】:
-
loc、new_cols和sql的内容是什么reproducible example可以吗? -
你在
paste0中粘贴或尝试粘贴什么? -
我对其进行了测试,它可以工作到 255 并且不适用于高于 255 的值。也许
gsub只接受{n}正则表达式中最大大小为一个字节的值?!跨度> -
这确实是一个尴尬的错误......
-
对不起,这只是我实际代码中的一个工件,我用它来构建正则表达式。粘贴或不粘贴都会出现同样的错误。