For example, consider the following regular expression that matches the date:
Copy codeThe Code is as follows: // \ ((? : 19 | 20) [0-9] {2}) [\-\/.] (0 [1-9] | 1 [012]) [\-\/.] (0 [1-9] | [12] [0-9] | 3 [01]) \ z/
After Re is used, regular expressions can be constructed step by step based on short and easy-to-read expressions. For example:
Copy codeThe Code is as follows:
Require 'Re'
Include Re
Delim = re. any ("-/.")
Century_prefix = re ("19") | re ("20 ")
Under_ten = re ("0") + re. any ("1-9 ")
Ten_to_twelve = re ("1") + re. any ("012 ")
Ten_and_under_thirty = re. any ("12") + re. any ("0-9 ")
Thirties = re ("3") + re. any ("01 ")
Year = (century_prefix + re. digit. repeat (2). capture (: year)
Month = (under_ten | ten_to_twelve). capture (: month)
Day = (under_ten | ten_and_under_thirty | thirties). capture (: day)
Date = (year + delim + month + delim + day). all
Although the amount of Code has increased, each part is very short and small, and it is easy to verify. At the same time, the captured part can be accessed through the corresponding variable name:
Copy codeThe Code is as follows:
Result = date. match ("2009-01-23 ")
Result [: year] # => "2009"
Result [: month] # => "01"
Result [: day] # => "23"
Note that building a regular expression with Re will be slow, so it is recommended to create a regular expression and reuse it. When matching, the performance is very similar to the native regular expression. (Additional method calls and Re: Result creation to return matching results affect a little bit of performance .) If you need to pursue the ultimate performance, you can still use Re to construct regular expressions, and then extract the original Ruby Regexp to match. In this way, the performance is the same as using native regular expressions.
For example, construct a regular expression that matches the phone number:
Copy codeThe Code is as follows:
PHONE_RE = re. digit. repeat (3). capture (: area) +
Re ("-") +
Re. digit. repeat (3). capture (: exchange) +
Re ("-") +
Re. digit. repeat (4). capture (: subscriber)
Then extract the original regular object and use it to match:
Copy codeThe Code is as follows:
PHONE_REGEXP = PHONE_RE.regexp
If PHONE_REGEXP = ~ String
# Blah
End