我在 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 {}'
背景
R gsub
默认使用 TRE 正则表达式库。限制量词的边界从 0 到RE_DUP_MAX
这是在 TRE 代码中定义的。看此 TRE 参考 http://laurikari.net/tre/documentation/regex-syntax/:
A bound是以下之一,其中n
and m
are 之间的无符号十进制整数0
and RE_DUP_MAX
看来RE_DUP_MAX
设置为 255(参见此TRE源文件 https://github.com/laurikari/tre/blob/556ef09df29aadc041923522d07cc012d92a4749/include/tre/tre.h#L128显示#define RE_DUP_MAX 255
),因此,您不能在{n,m}
限制量词。
Solution
使用 PCRE 正则表达式风格,添加perl = TRUE
它会起作用的。
R demo https://ideone.com/elpMNU:
> 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('^(.{273})(.+)$', new_cols, sql, perl=TRUE)
[1] "happy"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)