3

This is one of the most difficult things to search for because when you search how to parse a regex you get how to parse with a regex. I want to read a regex from a file, put it in an object somehow, then parse strings using that regex in my program.

Im sure someone has done this before, can you help me out on where to start?

4 Answers 4

3

You can use Regexp.new to create a regex from a string. So if your file contains only the regex you can do:

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

(chomp to remove the trailing newline if there is one, assuming you don't want that in the regex)

Sign up to request clarification or add additional context in comments.

Comments

2
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

1 Comment

Hm... SO's syntax highlighting doesn't know class IO?
0

YAML for ruby supports regexes.

Comments

0

Yep, this is an oldie, but I was also wanting to do a similar thing.

Not sure when it was introduced, but there is a Regexp.compile command that solves your/our problem.

File contents (eg.yaml):

---
my_regexp: ^feature\/

Example code:

require 'yaml'
config = YAML.load_file('eg.yaml')
rgx = Regexp.compile(config['my_regexp'])

puts 'No output, as it does not match' if 'hotfix/FU-123' =~ rgx
puts 'No output, as it starts with something different' if 'new_feature/FU-123' =~ rgx
puts 'Winner winner, chicken dinner' if 'feature/BAR-123' =~ rgx

As Andrew Grimm points out, it is possible to serialise the YAML to include hints. I personally find this to be problematic with config files that can be edited by humans.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.