lispとrubyとpythonと その6 正規表現(ruby)

Rubyでの正規表現

# -*- coding: utf-8 -*-
#正規表現リテラルは/で囲む

#Regexp.new(...)でもいい
rx = /(?<p>.*):\/\/(?<d>.*)\//
target = "http://faroffsea.blogspot.com/"

#matchの戻り値はMatchData
captures = rx.match target
#/(?<p>.*):\/\/(?<d>.*)\//.match "http://faroffsea.blogspot.com/"

puts captures[0]
#->http://faroffsea.blogspot.com/

puts captures[1]
#->http

puts captures[2]
#->faroffsea.blogspot.com

puts captures["p"]
#->http

puts captures["d"]

#->faroffsea.blogspot.com
#union
#引数の正規表現を|でつなぐ
rx = Regexp.union(/aaa/,/bbb/,/ccc/)
#=>/(?-mix:aaa)|(?-mix:bbb)|(?-mix:ccc)/

rx.match("aaaxxxbbbcccdddaaa").to_s
#=>"aaa"

rx = /(?<p>.*):\/\/(?<d>.*)\//
target = "http://faroffsea.blogspot.com/"
rx.match target

#カレントスコープで最後に行った正規表現マッチの MatchData オブジェクトが返る
Regexp.last_match
#=>#<MatchData "http://faroffsea.blogspot.com/" p:"http" d:"faroffsea.blogspot.com">

#$~はlast_matchと同じ意味
$~
#<MatchData "http://faroffsea.blogspot.com/" p:"http" d:"faroffsea.blogspot.com">

#last_match[0]と$&も同じ意味
#マッチした文字列を返す
Regexp.last_match[0]
#=>"http://faroffsea.blogspot.com/"

#last_match[n]と$nも同じ意味(nは0以外)
Regexp.last_match[1]
#=>"http"

$1
#=>"http"

Regexp.last_match[2]
#=>"faroffsea.blogspot.com"

$2
#=>"faroffsea.blogspot.com"

#置換
"aaa abc aaabc cccaaabbb".sub /aaa/, "xxx"
#=>"xxx abc aaabc cccaaabbb"

#gsubだと全部置き換え
"aaa abc aaabc cccaaabbb".gsub /aaa/, "xxx"
#=>"xxx abc xxxbc cccxxxbbb"

"aaa abc axy".gsub /a../ do |e|
  puts ":" + e.to_s
  "aaa"
end
#->:aaa
#  :abc
#  :axy
#=>"aaa aaa aaa"

rx = /a/

#$_には最後にgetsかreadlineで読み込んだ文字列が入ってる
readline
#ここでaaa入力

$_
#=>"aaa\n"

#~で$_との間でマッチさせる
~ rx
#=>0