落書きノート

ふと自分が気になった事を書いてます

Ruby資格技術者問題集

今回は正規表現についてです。

irb(main):001:0> /Ruby/
=> /Ruby/
irb(main):002:0> %r(Ruby)
=> /Ruby/
irb(main):003:0> Regexp.new "Ruby"
=> /Ruby/
irb(main):004:0> /Ruby/ === "I love Ruby"
=> true
irb(main):005:0> p case "I love Ruby"
irb(main):006:1> when /Ruby/ then; "Ruby!"
irb(main):007:1> when /Java/ then; "Java!"
irb(main):008:1> end
"Ruby!"
=> "Ruby!"
irb(main):009:0> /Ruby/ =~ "I love Ruby"
=> 7
irb(main):010:0> "I love Ruby" =~ /Ruby/
=> 7
irb(main):011:0> /bb/ =~ "aabbcc"
=> 2
irb(main):012:0> p $`
"aa"
=> "aa"
irb(main):013:0> p $&
"bb"
=> "bb"
irb(main):014:0> p $'
"cc"
=> "cc"
irb(main):015:0> reg = /^(aa|bb)c$/
=> /^(aa|bb)c$/
irb(main):016:0> reg === "aac"
=> true
irb(main):022:0> reg === "bbc"
=> true
irb(main):023:0> reg = /a[bcd]e[fg]h/
=> /a[bcd]e[fg]h/
irb(main):024:0> reg === "abegh"
=> true
irb(main):025:0> /a[1-5]z/ === "a2z"
=> true
irb(main):026:0> /a[b-d]z/ === "abz"
=> true
irb(main):027:0> /a\db/ === "a2b"
=> true
irb(main):028:0> p /a(bc)*d/ === "abcbcd"
true
=> true
irb(main):029:0> %r|(http://www(\.)(.*)/)| =~ "http://www.xyz.org/"
=> 0
irb(main):030:0> p $1
"http://www.xyz.org/"
=> "http://www.xyz.org/"
irb(main):031:0> p $2
"."
=> "."
irb(main):032:0> p $3
"xyz.org"
=> "xyz.org"
irb(main):033:0> p $4
nil
=> nil
irb(main):034:0> /ruby/ === "RUBY"
=> false
irb(main):035:0> /ruby/i === "RUBY"
=> true
irb(main):036:0> /a.*b/ === "a\nb"
=> false
irb(main):037:0> /a.*b/m === "a\nb"
=> true
irb(main):038:0> puts `date`
201679日 土曜日 151136JST
=> nil

次回はブロックとProcについてです。あまりやったことがないので楽しみですね。