Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to DRY ruby regex?

Tags:

regex

ruby

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!

like image 568
Epigene Avatar asked Apr 25 '26 13:04

Epigene


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 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.

like image 70
Roney Michael Avatar answered Apr 28 '26 04:04

Roney Michael


You can do it with regular ruby

date_regex = /\d{1,2}-\d{1,2}-\d{4}/
/\A(#{date_regex})...?(#{date_regex})\z/
like image 26
Sergio Tulentsev Avatar answered Apr 28 '26 02:04

Sergio Tulentsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!