是否可以从 Ruby 中的外部文件加载正则表达式?

发布于 2024-11-29 11:12:09 字数 209 浏览 6 评论 0原文

我想从 Ruby 中的外部文件读取正则表达式。例如,我想替换一个大字符串,从文件中加载每个正则表达式并为每个正则表达式运行 gsub 。每个正则表达式在文件上由换行符分隔。

外部文件将是这样的:

engenharia d[ae] computação
ci[êe]ncias? d[ae] computação

可能吗?

I want to read regular expressions from a external file in Ruby. For example, I want to substitute a big string loading every regex from a file and running gsub for each. Each regex is separated by newlines on the file.

The external file would be like this:

engenharia d[ae] computação
ci[êe]ncias? d[ae] computação

Is it possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

云淡风轻 2024-12-06 11:12:09

当然!您只需使用 Regex.new "my string" 即可创建正则表达式。将其与读取文件放在一起:

regexen = []
File.open("myfile.txt", "r") do |f|
  while line = f.gets.chomp
    regexen << Regexp.new line
  end
end

Sure! You can create a regex simply by using Regex.new "my string". To put it together with reading a file:

regexen = []
File.open("myfile.txt", "r") do |f|
  while line = f.gets.chomp
    regexen << Regexp.new line
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文