2016-05-19 21 views
5

Sto usando gsub in R per aggiungere del testo nel mezzo di una stringa. Funziona perfettamente ma per qualche motivo, quando la posizione diventa troppo lunga genera un errore. Il codice è qui sotto:Problemi con gsub e regex in R

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 {}' 

Questo codice funziona bene quando il numero tra parentesi (273 in questo caso) è meno, ma non quando si tratta di questo grande.


Questo produce l'errore:

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 {}' 
+2

Qual è il contenuto di 'loc',' 'new_cols' e sql'can si effettua una [esempio riproducibile] (http://stackoverflow.com/questions/5963269/how -to-make-a-great-r-riproducibile-esempio/5965451 # 5965451) per favore? –

+1

Cosa stai incollando o cercando di incollare in 'paste0'? – Parfait

+1

Lo collaudo e funziona fino al 255 e non funziona per valori superiori a 255. Forse 'gsub' accetta solo valori' {n} 'solo fino a una dimensione di un byte nelle espressioni regolari ?! – FlorianSchunke

risposta

13

Sfondo

R gsub utilizza la libreria di espressioni regolari TRE per impostazione predefinita. I limiti del quantificatore limite sono validi da 0 fino a RE_DUP_MAX definito nel codice TRE. Vedere this TRE reference:

A bound is one of the following, where n and m are unsigned decimal integers between 0 and RE_DUP_MAX

Sembra che il RE_DUP_MAX è impostato su 255 (si veda questo TRE source file mostrando #define RE_DUP_MAX 255), e, quindi, non è possibile utilizzare più {n,m} limitare quantifier.

Soluzione

Usa PCRE regex sapore, aggiungere perl = TRUE e funzionerà.

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

Grazie! Funziona alla grande! – Soxman

+1

@David, 'perl = T' =' perl = TRUE'. –

+3

[Non si dice ...] (http://www.r-bloggers.com/r-tip-avoid-using-t-and-f-as-synonyms-for-true-and-false/) –