Hi guys, I try to do something, but like usual, I am not good with regex
Basically, I would like with a regex to catch all texts starting with a $ (uppercase only or containing as well number), and replace it by ENV[“textvalue”]
Example:
puts "/usr/bin:$PATH:/usr/share:$NUT".gsub(/(\$)([A-Z0-9])\w+/,"ENV[\"\1\"]")
Expected result:
/usr/bin:ENV["PATH"]:/usr/share:ENV["NUT"]
puts "/usr/bin:$PATH:/usr/share:$NUT".gsub(/\$([A-Z0-9]+)/,"ENV[\"\\1\"]")
Seems to do the trick.
1 Like
And when the regex catch the environment variable, if I want to replace by the value of that var in the system ?
I tried that but don’t work:
puts "/usr/bin:$PATH1:/usr/share:$NUT".gsub(/\$([A-Z0-9]+)/,"#{ENV["\\1"]}")
You’d probably want to use the block version of #gsub
in that case, so you can access the match group for each ENV var:
"/usr/bin:$PATH1:/usr/share:$NUT".gsub(/\$([A-Z0-9]+)/) do |_, match|
ENV[match[1]]
end
1 Like
Thanks a lot. It’s exactly what I need
Just want to mention: https://rubular.com :)
It’s been my goto website for building and testing regular expressions, ever since I was introduced to Ruby back in 2009.
Crystal uses a different Regex engine than Ruby, so it might not be the best option for testing Crystal regexes. I usually use https://regexr.com/, but be sure to change the engine to PCRE
instead of Javascript
as it defaults to towards the top right.