How to escape all characters with special meaning in Regex

后端 未结 2 556
星月不相逢
星月不相逢 2021-01-24 14:23

I just stumbled upon the following which I can\'t quite get my head around. When you create a new Regexp in Ruby like so:

Regexp.new(\'http://www.example.com\')
         


        
相关标签:
2条回答
  • 2021-01-24 14:55

    You can do:

    Regexp.escape('http://www.example.com')
    

    That will return the fully escaped string

    0 讨论(0)
  • 2021-01-24 14:56

    Alternatively, if you just need to check whether a given text contains the specified url you can use String#include?, and drop the regex altogether. Bearing in mind that Ruby will just do simple string comparisons, this should also be faster.

    # before
    if text =~ Regexp.new(Regexp.escape('http://www.example.com'))
      ...
    end
    
    # after
    if text.include?('http://www.example.com')
      ...
    end
    
    0 讨论(0)
提交回复
热议问题