For example, consider the following regular expression for the matching date:
Copy Code code as follows:
/\a ((?: 19|20) [0-9]{2}) [\-\/.] (0[1-9]|1[012]) [\- \/.] (0[1-9]| [12] [0-9]|3[01]) \z/
With the RE, regular expressions can be built on a short, readable expression, step-by-step, for example:
Copy Code code 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 ("a") + 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 (:d ay)
Date = (year + delim + month + Delim + day).
Although the amount of code is increased, each part is short and easy to verify. At the same time, the captured part can be accessed by the corresponding variable name:
Copy Code code as follows:
result = Date.match ("2009-01-23")
Result[:year] # => "2009"
Result[:month] # => "01"
result[:d ay] # => "23"
Note that it is slow to build regular expressions with re, so it is recommended that you create regular expressions and reuse them. When matched, the performance is very close to the native regular expression. (Additional method calls and create Re::result to return matching results affect a little bit of performance.) If you need to pursue extreme performance, you can still use the RE to build regular expressions and then extract the original Ruby regexp to match. In this way, performance is the same as using native regular expressions.
For example, to build a regular expression that matches a phone number:
Copy Code code as follows:
Phone_re = Re.digit.repeat (3). Capture (: Area) +
Re ("-") +
Re.digit.repeat (3). Capture (: Exchange) +
Re ("-") +
Re.digit.repeat (4)). Capture (: Subscriber)
It then extracts the original regular object and uses it directly to match:
Copy Code code as follows:
Phone_regexp = Phone_re.regexp
If Phone_regexp =~ string
# blah blah blah
End