Rで正規表現 のバックアップの現在との差分(No.1) - アールメカブ

アールメカブ


Rで正規表現 のバックアップの現在との差分(No.1)


  • 追加された行はこの色です。
  • 削除された行はこの色です。
[[Rの備忘録]]

#contents

* 基本関数の機能 [#ub6ba380]
 ex.txt <- c("青空文庫","青い鳥文庫")
- nchar()

 > nchar(ex.txt)
 [1] 4 5

-substr()

 > substr(ex.txt, 1,3)
 [1] "青空文" "青い鳥"

- chartr()

 > chartr("青い鳥","岩波", ex.txt)
 以下にエラー chartr("青い鳥", "岩波", ex.txt) :
         'old' が 'new' より長いです 
 > chartr("青","岩波", ex.txt)
 [1] "岩空文庫"   "岩い鳥文庫"
   
- strsplit()

 > strsplit(ex.txt, "")
 [[1]]
 [1] "青" "空" "文" "庫"
 
 [[2]]
 [1] "青" "い" "鳥" "文" "庫"

-grep()

 > grep("鳥", ex.txt)
 [1] 2
 > grep("鳥", ex.txt, value = T)
 [1] "青い鳥文庫"

- regexpr()

 > regexpr("鳥", ex.txt)
 [1] -1  3              # -1 は該当なし
 attr(,"match.length")
 [1] -1  1              # 上記のベクトル(-1,3)の属性である.
 > attributes(regexpr("鳥", ex.txt)) # 出力はリスト
 $match.length
 [1] -1  1
 > attr( regexpr("鳥", ex.txt), "match.length") #出力はベクトル
 [1] -1  1
- gregexpr()

 > gregexpr("文庫", ex.txt)
 [[1]]
 [1] 3
 attr(,"match.length")
 [1] 2
 
 [[2]]
 [1] 4
 attr(,"match.length")
 [1] 2
 > unlist(gregexpr("文庫", ex.txt))
 [1] 3 4
 > sapply( gregexpr("文庫", ex.txt), attributes)
 $match.length
 [1] 2
 
 $match.length
 [1] 2
 
 > sapply( gregexpr("文庫", ex.txt), attr, "match.length")
 [1] 2 2

-gsub()

 > gsub("青", "赤", ex.txt)
 [1] "赤空文庫"   "赤い鳥文庫"

* 応用的な検索 [#b0f3e007]
  ex2.txt <- c("隣の客はよく柿食う客だ。",
               "すもももももももものうち。")

- gsub()

 > gsub("も.*も", "かき", ex2.txt)
 [1] "隣の客はよく柿食う客だ。" "すかきのうち。"  
 > gsub("(?U)も.*も", "かき", ex2.txt, perl = T)
 [1] "隣の客はよく柿食う客だ。"   "すかきかきかきかきのうち。"     
 > gsub("も.*?も", "かき", ex2.txt, perl = T)
 [1] "隣の客はよく柿食う客だ。"   "すかきかきかきかきのうち。"
 > gsub("も{1,4}", "かき", ex2.txt)
 [1] "隣の客はよく柿食う客だ。" "すかきかきのうち。"
    > gsub("[ま-も]", ex2.txt) ## さすがにこれは無理
    以下にエラー gsub("[ま-も]", ex2.txt) : 
       要素 1 は空です; 
     'is.character' の引数リストの評価されていた部分は: 
     (x)
 > gsub("(もも){1,4}", "もも", ex2.txt)
 [1] "隣の客はよく柿食う客だ。" "すもものうち。"          
  
 > gsub("\\w", "w",ex2.txt)
 [1] "wwwwwwwwwww。"  "wwwwwwwwwwww。"
 > gsub("\\w+", "w",ex2.txt)
 [1] "w。" "w。"
 >
 > gsub("(客)", "お\\1さん",ex2.txt)
 [1] "隣のお客さんはよく柿食うお客さんだ。"
 [2] "すもももももももものうち。"          
 >
* lookaround [#y3e910c5]
 > gsub("す(?=もも)", "おい", ex2.txt , perl = T)
 [1] "隣の客はよく柿食う客だ。"     "おいもももももももものうち。"