Tbpgr Blog

元エンジニア 人事 tbpgr(てぃーびー) のブログ

書籍 Regular Expressions Cookbook | Limit the Number of Lines in Text

パンくず

書籍 Regular Expressions Cookbook
Limit the Number of Lines in Text

概要

行数のバリデーション。

サンプル

subject = Array.new
subject << "1\n" # => \n=Unix,Linux
subject << "1\n2\n"
subject << "1\n2\n3\n"
subject << "1\r\n" # => \n=Windows
subject << "1\r\n2\r\n"
subject << "1\r\n2\r\n3\r\n"
subject << "1\r" # => \n=Mac
subject << "1\r2\r"
subject << "1\r2\r3\r"

pattern = /\A(?:[^\r\n]*(?>\r\n?|\n)){2}\z/ # => 行数2行チェック
subject.each_with_index {|each_subject,i|puts "#{i}:#{each_subject.scan(pattern)}"}

結果

0:[]
1:["1\n2\n"]
2:[]
3:[]
4:["1\r\n2\r\n"]
5:[]
6:[]
7:["1\r2\r"]
8:[]