1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

拡張子を除いたファイル名の先頭と末尾のみを String#gsub のみでマスキングする

Last updated at Posted at 2024-11-29

メモ

RUBY_VERSION
#=> "3.3.6"

require 'minitest/autorun'

class TestMaskFilename < Minitest::Test
  def mask_filename(filename)
    # 肯定後読みでファイル名の先頭 1 文字を指定する。
    # 肯定先読みでファイル名の末尾 1 文字と拡張子を指定する。
    # String#gsub のブロック引数には正規表現にマッチした部分文字列が渡されるので、
    # '*' を同じ長さだけ並べた文字列に置換することでマスキングする。  
    filename.gsub(/(?<=\A.).+(?=.\.\w+\z)/) { |matched| '*' * matched.length }
  end

  def test_mask_filename
    assert_equal('佐*****密.xlxs', mask_filename('佐倉杏子の秘密.xlxs'))
    assert_equal('佐**********s.zip', mask_filename('佐倉杏子の秘密.xlxs.zip'))
    assert_equal('M*************密.docx', mask_filename('Mr.Children の秘密.docx'))
  end
end
1
0
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?