The Ruby %r{ } expression

前端 未结 5 1129
暗喜
暗喜 2020-12-04 09:21

In a model there is a field

validates :image_file_name, :format => { :with => %r{\\.(gif|jpg|jpeg|png)$}i

It looks pretty odd for me.

相关标签:
5条回答
  • 2020-12-04 09:38

    With %r, you could use any delimiters.

    You could use %r{} or %r[] or %r!! etc.

    The benefit of using other delimeters is that you don't need to escape the / used in normal regex literal.

    0 讨论(0)
  • 2020-12-04 09:40

    %r{} is equivalent to the /.../ notation, but allows you to have '/' in your regexp without having to escape them:

    %r{/home/user}
    

    is equivalent to:

    /\/home\/user/
    

    This is only a syntax commodity, for legibility.

    Edit:

    Note that you can use almost any non-alphabetic character pair instead of '{}'. These variants work just as well:

    %r!/home/user!
    %r'/home/user'
    %r(/home/user)
    

    Edit 2:

    Note that the %r{}x variant ignores whitespace, making complex regexps more readable. Example from GitHub's Ruby style guide:

    regexp = %r{
      start         # some text
      \s            # white space char
      (group)       # first group
      (?:alt1|alt2) # some alternation
      end
    }x
    
    0 讨论(0)
  • 2020-12-04 09:52

    \. => contains a dot
    (gif|jpg|jpeg|png) => then, either one of these extensions
    $ => the end, nothing after it
    i => case insensitive

    And it's the same as writing /\.(gif|jpg|jpeg|png)$/i.

    0 讨论(0)
  • 2020-12-04 09:55

    this regexp matches all strings that ends with .gif, .jpg...

    you could replace it with

    /\.(gif|jpg|jpeg|png)$/i
    
    0 讨论(0)
  • 2020-12-04 09:55

    It mean that image_file_name must end ($) with dot and one of gif, jpg, jpeg or png.

    Yes %r{} mean exactly the same as // but in %r{} you don't need to escape /.

    0 讨论(0)
提交回复
热议问题