[英]In R, how can I manipulate variable in dataframe using regular expression?
[英]Using regular expression, how can I add elements after I find a match in r?
我有一列具有數字長度范圍為 10 和 11 的字符串。這是列中一些值的示例:
column=c("5699420001","00409226602")
如何在前四位數字之后(在 10 個字符的字符串中)和前五位數字之后(在具有 11 個字符的字符串中)以及兩個長度的后四位數字之后放置連字符? Output 在下面提供。 我想為此使用stringr
。
column_standard=c("5699-4200-01","00409-2266-02")
嘗試使用這個作為你的表達:
\b(\d{4,5})(\d{4})(\d{2}\b)
它設置了三個捕獲組,您以后可以在替換中使用它們來輕松地在它們之間添加連字符。
然后你只需替換為:
\1-\2-\3
感謝@Dunois 指出它在代碼中的外觀:
column_standard <- sapply(column, function(x) stringr::str_replace(x, "^(\\d{4,5})(\\d{4})(\\d{2})", "\\1\\-\\2-\\3"))
這是一個活生生的例子。
這是使用帶有stringr
的str_replace()
function 的捕獲組的解決方案:
library(stringr)
column <- c("5699420001","00409226602")
column_standard <- sapply(column, function(x){
ifelse(nchar(x) == 11,
stringr::str_replace(x, "^([0-9]{5})([0-9]{4})(.*)", "\\1\\-\\2-\\3"),
stringr::str_replace(x, "^([0-9]{4})([0-9]{4})(.*)", "\\1\\-\\2-\\3"))
})
column_standard
# 5699420001 00409226602
# "5699-4200-01" "00409-2266-02"
代碼應該是不言自明的。 我可以根據要求提供詳細的解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.