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

ドキュメントから:

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 に答える
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 に答える