0

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

这有效:

 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 
4

2 回答 2

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
于 2013-07-02T05:55:09.747 回答
1

文档

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: \.

于 2013-07-02T06:02:28.227 回答