Way to DRY ruby regex?
I have this regex to check if a string has a format date, two or three dots, date
/\A(\d{1,2}-\d{1,2}-\d{4})...?(\d{1,2}-\d{1,2}-\d{4})\z/
As you can see, the date matching group is being repeated \d{1,2}-\d{1,2}-\d{4}
.
Is there a normal or normal ruby programming way to assign this group to a variable and then use it in a regex rather than a real group, giving me something like /\A<var>...?<var>\z/
?
Thank!
+3
source to share
2 answers
Regex concatenation should do the trick.
From the discussion here :
irb(main):001:0> re1 = re1 = /[\w]+/
=> /[\w]+/
irb(main):002:0> re2 = /[\d]+/
=> /[\d]+/
irb(main):003:0> re3 = /#{re1}[\s]+#{re2}/
=> /(?-mix:[\w]+)[\s]+(?-mix:[\d]+)/
irb(main):004:0> "Foo 123".match(re3).to_s
=> "Foo 123"
For your code:
irb(main):001:0> re1 = /\d{1,2}-\d{1,2}-\d{4}/
=> /\d{1,2}-\d{1,2}-\d{4}/
irb(main):002:0> re2 = /\A(#{re1})...?(#{re1})\z/
=> /\A((?-mix:\d{1,2}-\d{1,2}-\d{4}))...?((?-mix:\d{1,2}-\d{1,2}-\d{4}))\z/
.. and then use re2 as desired.
+1
source to share