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
以上是应用 RegexBuilder 书写正则表达式例如 IP 地址的一个例子.
RegexBuilder 的目的是试图增强正则表达式的可读性和可维护性
RegexBuilder 并不是用来取代 Regexp 的, 而是辅助编写 Regexp 构造函数需要的第一个参数.
RegexBuilder 包含了正则表达式符号(Anchors/Character Classes/Repetition/Alternation/Grouping)到 API 的一一对应, 如 one_of => |, either => [], at_least_one => + 等.
RegexBuilder 还包含了可以直接使用的一组常见的正则表达式, 如 IP 地址, Email 地址等.
RegexBuilder 使用了Java风格的API而不是Ruby风格的API, 如 repeat(3, digit()) 而不是 digit(:repeat => 3)
RegexBuilder 还没实现Substitutions, 如 /0, /1, /& 等.
安装下载
gem install regexbuilder
RegexBuilder tries to improve the readability and maintainability of regular expression.
RegexBuilder does not intend to replace the Regexp class, while it just helps to create the first parameter of the ctor of Regexp.
RegexBuilder maps the symbols of regular expression (Anchors/Character Classes/Repetition/Alternation/Grouping) to API, like one_of => |, either => [], at_least_one => + ,etc.
RegexBuilder supports a group of regular expression which are used frequently, such as IP and Email address.
RegexBuilder uses Java style API rather than Ruby Style API, like repeat(3, digit()) , but not digit(:repeat => 3)
RegexBuilder does not support Substitutions for now, like /0, /1, /& etc.
Download and Install
gem install regexbuilder