LoginSignup
46
40

More than 5 years have passed since last update.

[Ruby]特定の文字列の抽出

Last updated at Posted at 2017-02-19

str[]メソッドを使う

str[]は、文字列の中から部分文字列を取り出すメソッド。

str[regexp, num]

第二引数が 0 の場合は、引数のない場合と同じ。
第二引数が 1 の場合は、マッチした()内の文字列が返る。

>> "株式会社ほげほげ(かぶしきがいしゃほげほげ)"[/((.*?))/, 0]
=> "(かぶしきがいしゃほげほげ)"
>> "株式会社ほげほげ(かぶしきがいしゃほげほげ)"[/((.*?))/, 1]
=> "かぶしきがいしゃほげほげ"

括弧内の文字列を取り出す際は、第二引数を 1 にすればいける。

他の使い方

str[idx]

idxの位置の文字を返す。

>> s = "hello"
=> "hello"
>> s[1]
=> "e"

str[idx, len]

idxの位置からlen文字の文字列を返す。

>> s = "hello"
=> "hello"
>> s[1, 3]
=> "ell"

str[range]

範囲を指定すると、範囲に一致する値を返す。

>> s = "hello, world"
=> "hello, world"
>> s[7..10]
=> "worl"
>> s[-5..-1]
=> "world"

str[regexp]

マッチした文字列が返る。(第二引数が0の場合と同じ挙動)

>> "株式会社ほげほげ(かぶしきがいしゃほげほげ)"[/\((.*?)\)/]
=> "(かぶしきがいしゃほげほげ)"

str[other_str]

一致する 文字列 を返す。
一致しない場合は nil を返す。

>> s = "hello, world"
=> "hello, world"
>> s["world"]
=> "world"
>> s["hoge"]
=> nil

参考リンク

http://ref.xaio.jp/ruby/classes/string/element_ref
https://docs.ruby-lang.org/ja/1.9.3/method/String/i/=5b=5d.html
http://d.hatena.ne.jp/riocampos+tech/20130630/p1

46
40
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
46
40