Rails - 如何将regex设置为方法?

时间:2016-03-05 22:54:27

标签: ruby-on-rails regex ruby-on-rails-4

我有一个正则表达式,我想用于字数统计和验证。但是,如果我决定更改正在使用的正则表达式,我不想进入每个模型和控制器。有没有办法创建一个定义正则表达式的辅助方法?

这是我尝试过的,但它不起作用:

module ApplicationHelper

  def word_count(content_text)
    content_text.scan(scan_regex).size
  end

  def scan_regex
    return "/\b(([a-zA-Z’'-]))+((?![^<>]*>)+(?![^&;]*;))\b/"
  end

end

1 个答案:

答案 0 :(得分:3)

你可以从正则表达式中删除'/',然后将它们添加到scan:

module ApplicationHelper

  def word_count(content_text)
    content_text.scan(/#{scan_regex}/).size
  end

  def scan_regex
    return "\b(([a-zA-Z’'-]))+((?![^<>]*>)+(?![^&;]*;))\b"
  end

end