使用带括号的文本作为rails中的参数搜索文本

时间:2013-07-02 05:53:00

标签: ruby-on-rails ruby ruby-on-rails-3

我有一个文本文件,我正在尝试阅读该文本文件,并找到与我的正则表达式匹配的所有文本。 它的参数没有括号时效果很好。

这有效:

 from_str = "this is a text"

当文本包含括号时,它不起作用。

from_str = "this is a text with (parenthesis)"

这是我的完整代码:

 from_str = "this is a text with (parenthesis)"
 str_to_text = "Freddie Mac Form"
 text = File.open(texturl).read
 text = text.scan(/#{from_str}(.*?)#{str_to_text}/m)[0]
 abort text.to_s    # Returning no data 

2 个答案:

答案 0 :(得分:1)

使用Regexp.escape转义变量。

from_str = "this is a text with (parenthesis)"
str_to_text = "Freddie Mac Form"
text = File.open(texturl).read
text = text.scan(/#{Regexp.escape(from_str)}(.*?)#{Regexp.escapestr_to_text)}/m)[0]
abort text.to_s    # Returning data

答案 1 :(得分:1)

来自documentation

The following are metacharacters (, ), [, ], {, }, ., ?, +, *. They have a specific meaning when appearing in a pattern. To match them literally they must be backslash-escaped. To match a backslash literally backslash-escape that: \.