简体   繁体   English

Ruby:如何从文件中读取正则表达式,然后使用该正则表达式解析字符串?

[英]Ruby: How can I read a regex from a file, then parse strings using that regex?

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? 我确定之前有人这样做了,你能帮助我从哪里开始吗?

You can use Regexp.new to create a regex from a string. 您可以使用Regexp.new从字符串创建正则表达式。 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) chomp删除尾随的换行符(如果有),假设你不希望在正则表达式)

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

YAML for ruby 支持正则表达式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM