R语言中sub函数的用法
1、
> sub("b", "x", c("abbc", "bbcd", "cde")) ## 三个字符串中第一个“b”被替换为了“x” [1] "axbc" "xbcd" "cde"
> gsub("b", "x", c("abbc", "bbcd", "cde")) ##gsub中的g表示全局, 即所有的“b”都被替换为了“x” [1] "axxc" "xxcd" "cde"
2、sub/gsub可以应用正则
> sub("^a","x",c("abcd","dcba")) ##^a表示开头的a, 即开头的a被替换为x [1] "xbcd" "dcba"
> sub("a$","x",c("abcd","dcba")) ##a$表示结尾的a, 即结尾的a被替换为x [1] "abcd" "dcbx"
> sub("a.c","x",c("abcd","sdacd")) ##.表示任一个,即abc被替换为x [1] "xd" "sdacd"
> sub("a*b","x",c("aabcd","dcaaaba")) ## *表示将前面的一个字符匹配0个至任意多个,即aab和aaab同时被替换为了x [1] "xcd" "dcxa"
> sub("a.*e","x",c("abcde","edcba")) ## 将a及其后任意字符1次至多次至e替换为x, 即将abcde替换为x [1] "x" "edcba" > sub("a*e","x",c("abcde","edcba")) ## 将0个至多个a到e的字符替换为x,即将e替换为了x [1] "abcdx" "xdcba"
> sub("ab|ba","x",c("abcd","dcba")) ##将ab或者ba替换我x [1] "xcd" "dcx"
> sub("[^ab]","x",c("abcd","dcba")) ## 将非ab的字符替换为x,只替换第一个 [1] "abxd" "xcba" > gsub("[^ab]","x",c("abcd","dcba")) ## g表示全局 [1] "abxx" "xxba"
> sub("[ab]","x",c("abcd","dcba")) ## 将a和b替换为x [1] "xbcd" "dcxa" > gsub("[ab]","x",c("abcd","dcba")) ## g表示全局 [1] "xxcd" "dcxx"
> sub("[a-c]","x",c("abcde","edcba")) ## 将a-c中的任一个替换为x [1] "xbcde" "edxba" > gsub("[a-c]","x",c("abcde","edcba")) ## g表示全局 [1] "xxxde" "edxxx"
> sub("[1-9]","x",c("ab001","001ab")) ## 将1-9中的任一字符替换我x [1] "ab00x" "00xab"
> sub("a.*b","x",c("aabab","eabbe")) ## 将a后1至任意多个字符到b替换为x [1] "x" "exe"
> sub("a.*b","x",c("aabab","eabbe")) ## 没有?表示贪婪匹配 [1] "x" "exe" > sub("a.*?b","x",c("aabab","eabbe")) ## 有?表示非贪婪匹配 [1] "xab" "exbe"
来源:https://blog.csdn.net/ISMedal/article/details/79450820