解析用于匹配子字符串的字符串并替换为数据

时间:2014-08-02 17:41:26

标签: string ruby-on-rails-4 substring

我们说我在rails中有一些文字:

text = "A bunch of data goes in here: %@user.name%@, %@user.email%@, %@company.name%@, %@company.state%@ and then some other information as well"

我正在寻找解析该文本的最佳方法,以查找%@和另一个%@之间的所有子字符串,以便将其替换为实际数据。该文本不应该预期数据将以任何特定的顺序排列,理想情况下它应该能够将子字符串转换为对与子字符串匹配的局部变量的引用。

2 个答案:

答案 0 :(得分:1)

text = "A bunch of data goes in here: %@user.name%@, %@user.email%@, %@company.name%@, %@company.state%@ and then some other information as well"


placeholder = text[/\%\@.*?\%\@/]

while placeholder

  case placeholder
  when "%@user.name%@"
    text.sub!(/\%\@.*?\%\@/,"Steve")
  when "%@user.email%@"
    text.sub!(/\%\@.*?\%\@/,"steve@example.com")
  when "%@company.name%@"
    text.sub!(/\%\@.*?\%\@/,"Wayne Industries")
  when "%@company.state%@"
    text.sub!(/\%\@.*?\%\@/,"Gotham")
  else
    text.sub!(/\%\@.*?\%\@/,"unknown")
  end
  placeholder = text[/\%\@.*?\%\@/]
end

答案 1 :(得分:1)

使用String#scan方法。

特别是对于你的情况,我以前匹配的正则表达式是:/(\\\\ t。*。* \%。@)/

text = "A bunch of data goes in here: %@user.name%@, %@user.email%@, %@company.name%@, %@company.state%@ and then some other information as well"

regex = /(\%\@.*?\%\@)/

#here's the one line version
text.scan(regex).each {|match| text.sub!(match[0], eval(match[0].gsub(/[\%\@]/, '')))}

#Here's the more organized version
text.scan(regex).each do |match| 
  current_match = match[0]
  replacement_var = current_match.gsub(/[\%\@]/, '')
  text.sub!(current_match, eval(replacement_var))
end

puts text