dak ブログ

python、rubyなどのプログラミング、MySQL、サーバーの設定などの備忘録。レゴの写真も。

前方一致する文字列を判定する正規表現

2010-12-21 01:17:45 | ruby
いくつかの文字列の中から、特定の文字列に前方一致するものを判定する方法です。
ちょっと強引ですが、正規表現でも実現できます。

【プログラム】

def make_prefix_match_regexp(str)
restr = '^'

cs = str.split('')
cs.each do |c|
restr << '(?:|' + Regexp.quote(c)
end

restr << ')' * cs.length + '$'

return restr
end


restr = make_prefix_match_regexp('http://test.jp/index.html')
re = Regexp.new(restr)
print("[#{restr}]\n")

['http://test.jp/',
'http://test.com/',
'http://test.jp/index.html',
'http://test.jp/index.html?p=1'].each do |str|
res = str =~ re
print("#{str}: [#{res.to_s}]\n")
end


【実行結果】
[^(?:|h(?:|t(?:|t(?:|p(?:|:(?:|/(?:|/(?:|t(?:|e(?:|s(?:|t(?:|\.(?:|j(?:|p(?:|/(?:|i(?:|n(?:|d(?:|e(?:|x(?:|\.(?:|h(?:|t(?:|m(?:|l)))))))))))))))))))))))))$]
http://test.jp/: [0]
http://test.com/: []
http://test.jp/index.html: [0]
http://test.jp/index.html?p=1: []