1.從一串字符中提取數(shù)字
#extract digits - all 4 works
string <- "My roll number is 1006781"
gsub(pattern = "[^0-9]",replacement = "",x = string)
stringi::stri_extract_all_regex(str = string,pattern = "\\d+") #list
regmatches(string, regexpr("[0-9]+",string))
regmatches(string, regexpr("[[:digit:]]+",string))
2.從一串字符串中刪除空格
#remove space
gsub(pattern = "[[:space:]]",replacement = "",x = "and going there today tomorrow")
gsub(pattern = "[[:blank:]]",replacement = "",x = "and going there today tomorrow")
gsub(pattern = "\\s",replacement = "",x = "and going there today tomorrow")
3.如果向量中存在值,則返回
#match values
det <- c("A1","A2","A3","A4","A5","A6","A7")
grep(pattern = "A1|A4",x = det,value =T)
4.提取鍵值對(duì)中可用的字符串
d <- c("(monday :: 0.1231313213)","tomorrow","(tuesday :: 0.1434343412)")
grep(pattern = "\\([az]+ :: (0\\.[0-9]+)\\)",x = d,value = T)
regmatches(d,regexpr(pattern = "\\((.*) :: (0\\.[0-9]+)\\)",text = d))
說(shuō)明:您可能會(huì)發(fā)現(xiàn)理解起來(lái)很復(fù)雜,所以讓我們一點(diǎn)一點(diǎn)地看一下。 “\(”用于轉(zhuǎn)義元字符?!癧az] +”匹配字母一次或多次?!埃? \。[0-9] +)”匹配十進(jìn)制值,其中元字符(。)被轉(zhuǎn)義使用雙反斜杠,周期也是如此。使用“[0-9] +”匹配數(shù)字。








暫無(wú)數(shù)據(jù)