I have this regex to check if a string is of 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 \d{1,2}-\d{1,2}-\d{4} is repeated.
Is there a regex-native or a general ruby programming way to assign this group to a variable and then use it in the regex, rather than the actual group, giving me something like /\A<var>...?<var>\z/?
Thanks!
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 specifically:
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.
You can do it with regular ruby
date_regex = /\d{1,2}-\d{1,2}-\d{4}/
/\A(#{date_regex})...?(#{date_regex})\z/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With