我有一个正则表达式,我想用于字数统计和验证。但是,如果我决定更改正在使用的正则表达式,我不想进入每个模型和控制器。有没有办法创建一个定义正则表达式的辅助方法?
这是我尝试过的,但它不起作用:
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
答案 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