2016-05-19 6 views
5

Ich benutze Gsub in R, um Text in der Mitte einer Zeichenfolge hinzuzufügen. Es funktioniert perfekt, aber aus irgendeinem Grund, wenn der Standort zu lang wird, wird ein Fehler ausgegeben. Der Code ist unten:Problem mit Gsub und 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 {}' 

Dieser Code funktioniert gut, wenn die Zahl in den Klammern (273 in diesem Fall) weniger ist, aber nicht, wenn es das ist groß.


Dies erzeugt den Fehler:

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

Was ist der Inhalt von 'ist loc',' new_cols' und 'sql'can Sie [reproduzierbares Beispiel] machen (http://stackoverflow.com/questions/5963269/how -zum-machen-ein-groß-r-reproduzierbar-beispiel/5965451 # 5965451) bitte? –

+1

Was fügen Sie in "paste0" ein? – Parfait

+1

Ich teste es und es funktioniert bis 255 und funktioniert nicht für Werte über 255. Vielleicht 'gsub' akzeptiert nur' {n} 'Werte nur bis zu einer Größe von einem Byte in Regexs ?! – FlorianSchunke

Antwort

13

Hintergrund

R gsub verwendet TRE regex Bibliothek standardmäßig. Die Grenzen in dem begrenzenden Quantifizierer sind gültig von 0 bis RE_DUP_MAX, was in dem TRE-Code definiert ist. Siehe this TRE reference:

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

Es scheint, dass die RE_DUP_MAX-255 gesetzt ist (siehe diese TRE source file#define RE_DUP_MAX 255 zeigt), und somit können Sie nicht mehr verwenden, in {n,m} quantifier begrenzen.

Lösung

Verwenden PCRE regex Geschmack, fügen Sie perl = TRUE und es wird funktionieren.

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

Danke! Funktioniert super! – Soxman

+1

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

+3

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