【问题标题】:Trouble with gsub and regex in RR中的gsub和正则表达式问题
【发布时间】: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 {}'

【问题讨论】:

  • locnew_colssql的内容是什么reproducible example可以吗?
  • 你在paste0中粘贴或尝试粘贴什么?
  • 我对其进行了测试,它可以工作到 255 并且不适用于高于 255 的值。也许 gsub 只接受 {n} 正则表达式中最大大小为一个字节的值?!跨度>
  • 这确实是一个尴尬的错误......
  • 对不起,这只是我实际代码中的一个工件,我用它来构建正则表达式。粘贴或不粘贴都会出现同样的错误。

标签: regex r gsub


【解决方案1】:

背景

R gsub 默认使用 TRE 正则表达式库。限制量词中的边界从 0 到 TRE 代码中定义的 RE_DUP_MAX 有效。见this TRE reference

绑定是以下之一,其中nm0RE_DUP_MAX 之间的无符号十进制整数

RE_DUP_MAX 似乎设置为 255(请参阅此 TRE source file 显示 #define RE_DUP_MAX 255),因此,您不能在 {n,m} 限制量词中使用更多。

解决方案

使用 PCRE 正则表达式风格,添加 perl = TRUE 即可。

R demo:

> 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"

【讨论】:

  • 谢谢!效果很好!
  • @David, perl=T = perl=TRUE.
  • 我可能错了,但它总是有效的。看起来类似于在 Perl 中使用 $&amp; 的问题。
  • @WiktorStribiżew 尝试:T&lt;-FALSE; T &amp;&amp; TRUE 并了解为什么在没有警告的情况下使用缩写是危险的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-09
  • 2019-11-17
相关资源
最近更新 更多