class IP
include RegexpBuilder
def
less_than_255
_0_to_100 =
repeat(digit(), 1,
2)
_100_to_200 =
"1" + _0_to_100
_200_to_250 =
"2" + either("0-4")
+ either("0-9")
_250_to_255 =
"25" + either("0-4")
one_of(_0_to_100,
_100_to_200, _200_to_250, _250_to_255)
end
def initialize
@ip_pattern
= repeat(group(group(less_than_255()) + literal(".")),
3) + group(less_than_255())
end
attr_reader
:ip_pattern
end
以上是應(yīng)用 RegexBuilder 書寫正則表達(dá)式例如 IP 地址的一個(gè)例子.
RegexBuilder 的目的是試圖增強(qiáng)正則表達(dá)式的可讀性和可維護(hù)性
RegexBuilder 并不是用來取代 Regexp 的, 而是輔助編寫 Regexp 構(gòu)造函數(shù)需要的第一個(gè)參數(shù).
RegexBuilder 包含了正則表達(dá)式符號(hào)(Anchors/Character
Classes/Repetition/Alternation/Grouping)到 API 的一一對應(yīng), 如 one_of => |, either
=> [], at_least_one => + 等.
RegexBuilder 還包含了可以直接使用的一組常見的正則表達(dá)式, 如 IP 地址, Email 地址等.
RegexBuilder 使用了Java風(fēng)格的API而不是Ruby風(fēng)格的API, 如 repeat(3,
digit()) 而不是 digit(:repeat
=> 3)
RegexBuilder 還沒實(shí)現(xiàn)Substitutions, 如 \0, \1, \& 等.
安裝下載
gem install regexbuilder
http://roll-stone.googlecode.com/svn/trunk/RegexBuilder/