Convert a string to regular expression ruby

前端 未结 5 1627
广开言路
广开言路 2020-12-12 20:19

I need to convert string like \"/[\\w\\s]+/\" to regular expression.

\"/[\\w\\s]+/\" => /[\\w\\s]+/

I tried using different Regexp

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-12 20:26

    This method will safely escape all characters with special meaning:

    /#{Regexp.quote(your_string)}/
    

    For example, . will be escaped, since it's otherwise interpreted as 'any character'.

    Remember to use a single-quoted string unless you want regular string interpolation to kick in, where backslash has a special meaning.

提交回复
热议问题