Convert a string to regular expression ruby

前端 未结 5 1616
广开言路
广开言路 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.

    0 讨论(0)
  • 2020-12-12 20:27

    To be clear

      /#{Regexp.quote(your_string_variable)}/
    

    is working too

    edit: wrapped your_string_variable in Regexp.quote, for correctness.

    0 讨论(0)
  • 2020-12-12 20:35

    Looks like here you need the initial string to be in single quotes (refer this page)

    >> str = '[\w\s]+'
     => "[\\w\\s]+" 
    >> Regexp.new str
     => /[\w\s]+/ 
    
    0 讨论(0)
  • 2020-12-12 20:38

    Using % notation:

    %r{\w+}m => /\w+/m
    

    or

    regex_string = '\W+'
    %r[#{regex_string}]
    

    From help:

    %r[ ] Interpolated Regexp (flags can appear after the closing delimiter)

    0 讨论(0)
  • 2020-12-12 20:43

    The gem to_regexp can do the work.

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

    You also can use the modifier:

    '/foo/i'.to_regexp => /foo/i
    

    Finally, you can be more lazy using :detect

    'foo'.to_regexp(detect: true)     #=> /foo/
    'foo\b'.to_regexp(detect: true)   #=> %r{foo\\b}
    '/foo\b/'.to_regexp(detect: true) #=> %r{foo\b}
    'foo\b/'.to_regexp(detect: true)  #=> %r{foo\\b/}
    
    0 讨论(0)
提交回复
热议问题