LoginSignup
0
0

More than 3 years have passed since last update.

正規表現を使った小技

Last updated at Posted at 2021-01-30

見つけたら都度書いていく。

特定の文字数で区切りたい

力技でやるマンだとこんな風に書いてしまうが、

text = 'abcdefghijklmn'
text.chars.each_slice(5).map(&:join)
# => ["abcde", "fghij", "klmn"]

正規表現だとこんなにスッキリ

text = 'abcdefghijklmn'
text.scan(/.{1,5}/)
# => ["abcde", "fghij", "klmn"]

単語境界というメタ文字がある

単語境界 \b
非単語境界 \B

ある文字列の中から先頭が0で始まる単語が存在するか

'10abcdes0fg'.match(/\b0\B/)
# => nil

'10abcdes 0fg'.match(/\b0\B/)
# => #<MatchData "0">

英数以外は空文字に置換

POSIXクラスというものがある

'asx., .pd[;m1@346lewmoefsm'.gsub(/[^[:alnum:]]/, '')
# => "asxpdm1346lewmoefsm"
0
0
0

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
0
0