2013-05-20 21 views
2

一月字符串的第N個點,我問如何替換字符串的第N個點:replace the first N dots of a string更換重新

迪文的回答是非常有益的。它可以被推廣嗎?

df.1 <- read.table(text = ' 

     my.string  other.stuff 

    1111111111111111  120 
    ..............11  220 
    11..............  320 
    1...............  320 
    .......1........  420 
    ................  820 
    11111111111111.1  120 

', header = TRUE) 

nn <- 14 

# this works: 

df.1$my.string <- sub("^\\.{14}", paste(as.character(rep(0, nn)), collapse = ""), 
df.1$my.string) 

# this does not work: 

df.1$my.string <- sub("^\\.{nn}", paste(as.character(rep(0, nn)), collapse = ""), 
df.1$my.string) 
+0

當然,但你必須用某種功能來代替,這樣就可以用適當的字符串長度每當更換匹配成功。例如在Perl中:'s/^ \。{1,14}(?= \ d)/'0'x length $&/ meg' – Qtax

+0

爲什麼downvote?這是一個寫得很好的問題,其中包括可重複的代碼 - 在這些方面比我們在附近看到的3/4或更多的問題要好... –

+0

很難理解~1.5k代表的某人如何期望在字符串來解決。但我刪除了我的downvote。 –

回答

3

使用sprintf你可以期望的輸出

nn <- 3 
sub(sprintf("^\\.{%s}", nn), 
    paste(rep(0, nn), collapse = ""), df.1$my.string) 

## [1] "1111111111111111" "000...........11" "11.............." 
## [4] "1..............." "000....1........" "000............." 
## [7] "11111111111111.1" 
0
pattstr <- paste0("\\.", paste0(rep(".",nn), collapse="") ) 
pattstr 
#[1] "\\..............." 
df.1$my.string <- sub(pattstr, 
         paste0(rep("0", nn), collapse=""), 
         df.1$my.string) 

> df.1 
     my.string other.stuff 
1 1111111111111111   120 
2 000000000000001   220 
3 11..............   320 
4 100000000000000   320 
5 00000000000000.   420 
6 00000000000000.   820 
7 11111111111111.1   120