我想要一個用於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;"
試試['stringB < - sub(「^((?:[^;] *;){4})。*」,「\\ 1」,stringA)'](http://ideone.com/257xfn)。 –
相關:http://stackoverflow.com/questions/26301424/split-on-first-nth-occurrence-of-delimiter – thelatemail
你總是可以使用strsplit,並避免完全複雜的正則表達式:'paste(strsplit(stringA, 「;」)[[1]] [1:4],collapse =「;」)'或甚至是substr(stringA,1,gregexpr(「;」,stringA)[[1]] [4])' – thelatemail