Split Ruby regex over multiple lines

后端 未结 4 1627
旧巷少年郎
旧巷少年郎 2020-12-13 11:48

This might not be quite the question you\'re expecting! I don\'t want a regex that will match over line-breaks; instead, I want to write a long regex that, for readability,

相关标签:
4条回答
  • 2020-12-13 12:18

    Using %r with the x option is the prefered way to do this.

    See this example from the github ruby style guide

    regexp = %r{
      start         # some text
      \s            # white space char
      (group)       # first group
      (?:alt1|alt2) # some alternation
      end
    }x
    
    regexp.match? "start groupalt2end"
    

    https://github.com/github/rubocop-github/blob/master/STYLEGUIDE.md#regular-expressions

    0 讨论(0)
  • 2020-12-13 12:25

    You need to use the /x modifier, which enables free-spacing mode.

    In your case:

    "bar" =~ /(foo|
               bar)/x
    
    0 讨论(0)
  • 2020-12-13 12:31

    Rather than cutting the regex mid-expression, I suggest breaking it into parts:

    full_rgx = /This is a message\. A phone number: \d{10}\. A timestamp: \d*?/
    
    msg = /This is a message\./
    phone = /A phone number: \d{10}\./
    tstamp = /A timestamp: \d*?/
    
    /#{msg} #{phone} #{tstamp}/
    

    I do the same for long strings.

    0 讨论(0)
  • 2020-12-13 12:34

    you can use:

    "bar" =~ /(?x)foo|
             bar/
    
    0 讨论(0)
提交回复
热议问题