2015-10-29 60 views
2

我想要一個用於R的子表達式的正則表達式替換字符串中第n個出現「;」之後的字符,在該字符串中,其中n是傳遞給正則表達式的可變數字。替換/刪除第n個字符串中的子串出現後

stringA="a; b; c; d; e; f; g; h; i; j;" 

    stringB<-sub("^(;){4}.*", "", stringA) 
##---------------^My attempt at a regular expression here------- 

所需的輸出:

stringB 
    "a; b; c; d;" 
+0

試試['stringB < - sub(「^((?:[^;] *;){4})。*」,「\\ 1」,stringA)'](http://ideone.com/257xfn)。 –

+0

相關:http://stackoverflow.com/questions/26301424/split-on-first-nth-occurrence-of-delimiter – thelatemail

+1

你總是可以使用strsplit,並避免完全複雜的正則表達式:'paste(strsplit(stringA, 「;」)[[1]] [1:4],collapse =「;」)'或甚至是substr(stringA,1,gregexpr(「;」,stringA)[[1]] [4])' – thelatemail

回答

3

您可以使用以下正則表達式:

^((?:[^;]*;){4}).* 

它匹配:

  • ^ - 字符串的開始
  • ((?:[^;]*;){4}) - (組1)捕獲的子串包含4個(或任何數量的傳遞與s變量)
    • [^;]*的出現 - 比;
    • ;其他0或多個符號 - 字面分號
  • .* - 0個或多個字符,儘可能多的

使用反向引用\\1在替換模式中,我們恢復結果中的前導子字符串。

IDEONE demo(這裏,極限閾值作爲字符串傳遞):

stringA="a; b; c; d; e; f; g; h; i; j;" 
s <- "4" 
stringB <- sub(sprintf("^((?:[^;]*;){%s}).*", s), "\\1", stringA) 
stringB 
## "a; b; c; d;" 

或者,如果你傳遞一個整數值

s <- 4 
sub(sprintf("^((?:[^;]*;){%d}).*", s), "\\1", stringA) 

another demo

+0

有沒有辦法在{n}中定義一個早先定義的變量「n」? – biotechris

+0

它是一個變量's',你可以在之前定義它。 –

+1

謝謝,這是有效的,我沒有注意到sprintf方法! – biotechris

相關問題