熱線電話:13121318867

登錄
首頁精彩閱讀R語言之正則表達式
R語言之正則表達式
2017-02-16
收藏

R語言正則表達式

正則表達式表通常被用來檢索、替換那些符合某個模式(規則)的文本。在我看來,正則表達式的主要用途有兩種:①查找特定的信息②查找并編輯特定的信息,也就是我們經常用的替換。。比如我們要在Word,記事本等里面使用快捷鍵Ctrl+F,進行查找一個特定的字符,或者替換一個字符,這就使用了正則表達式。

正則表達式的功能非常強大,尤其是在文本數據進行處理中顯得更加突出。R中的grep、grepl、sub、gsub、regexpr、gregexpr等函數都使用正則表達式的規則進行匹配。這幾個函數原型如下:

grep(pattern, x, ignore.case = FALSE, perl = FALSE, value = FALSE,

fixed = FALSE, useBytes = FALSE, invert = FALSE)

grepl(pattern, x, ignore.case = FALSE, perl = FALSE,

fixed = FALSE, useBytes = FALSE)

sub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,

fixed = FALSE, useBytes = FALSE)

gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,

fixed = FALSE, useBytes = FALSE)

regexpr(pattern, text, ignore.case = FALSE, perl = FALSE,

fixed = FALSE, useBytes = FALSE)

gregexpr(pattern, text, ignore.case = FALSE, perl = FALSE,

fixed = FALSE, useBytes = FALSE)

regexec(pattern, text, ignore.case = FALSE, perl = FALSE,

fixed = FALSE, useBytes = FALSE)

這里是對參數進行一個解釋說明。

接下來我們對這幾個函數談談他們的不同點。

 

 

 

現在來舉幾個例子。

首先使用[]中括號的功能,來查找一下看有沒有do組合的單詞。

text<-c("Don't","aim","for","success","if","you","want","it","just","do","what","you","love",

"and","believe","in","and","it","will","come","naturally")

#查找含有DO組合的單詞

grep("[Dd]o",text)#不區分大小寫

grep("[D]o",text)#D要大寫

grep("[d]o",text)#D小寫

運行結果如下:

> text<-c("Don't","aim","for","success","if","you","want","it","just","do","what",

"you","love","and","believe","in","and","it","will","come","naturally")

> 數據分析培訓

> #查找含有DO組合的單詞

> grep("[Dd]o",text)#不區分大小寫

[1]  1 10

> grep("[D]o",text)#D要大寫

[1] 1

> grep("[d]o",text)#D小寫

[1] 10 

郵箱匹配:

#郵箱匹配:

text2<-c("704232753@qq.com is my email address.")

grepl("[0-9.*]+@[a-z.*].[a-z.*]",text2)

結果如下

> text2<-c("704232753@qq.com is my email address.")

> grepl("[0-9.*]+@[a-z.*].[a-z.*]",text2)

[1] TRUE

說明可以查找到了。


數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢