Ruby: How can I read a regular expression from a file and then parse strings using this regular expression?

This is one of the most difficult things to find, because when you try to parse a regular expression, you get the opportunity to parse a regular expression. I want to read a regular expression from a file, put it in an object in some way, and then parse strings using this regular expression in my program.

I'm sure someone did this before, can you help me where to start?

+3
source share
3 answers

You can use Regexp.newto create a regular expression from a string. Therefore, if your file contains only a regular expression that you can do:

regex = Regexp.new( File.read("somefile").chomp )

( chompto remove the trailing newline, if there is one, if you do not want this in regular expression)

+3
source
r = /.ol/
File.open('test.txt','w') { |f| f.print r }
r = Regexp.new IO.read 'test.txt'
puts %w{rofl lol test lol2}.grep r
+2
source
0
source

Source: https://habr.com/ru/post/1764043/


All Articles