Ruby定义一个正则表达式

示例

可以在Ruby中以三种不同的方式创建Regexp。

  • 使用斜杠: / /

  • 使用 %r{}

  • 使用 Regex.new

    #以下形式是等效的
    regexp_slash = /hello/
    regexp_bracket = %r{hello}
    regexp_new = Regexp.new('hello')
    string_to_match = "你好,世界!"
    #所有这些将返回真实值
    string_to_match =~ regexp_slash    # => 0
    string_to_match =~ regexp_bracket  # => 0
    string_to_match =~ regexp_new      # => 0