Extract a substring from a string in Ruby using a regular expression

后端 未结 5 1812
栀梦
栀梦 2020-11-30 19:05

How can I extract a substring from within a string in Ruby?

Example:

String1 = \" \"

I want to extract

相关标签:
5条回答
  • 2020-11-30 19:26
    String1.scan(/<([^>]*)>/).last.first
    

    scan creates an array which, for each <item> in String1 contains the text between the < and the > in a one-element array (because when used with a regex containing capturing groups, scan creates an array containing the captures for each match). last gives you the last of those arrays and first then gives you the string in it.

    0 讨论(0)
  • 2020-11-30 19:33

    A simpler scan would be:

    String1.scan(/<(\S+)>/).last
    
    0 讨论(0)
  • 2020-11-30 19:36
    "<name> <substring>"[/.*<([^>]*)/,1]
    => "substring"
    

    No need to use scan, if we need only one result.
    No need to use Python's match, when we have Ruby's String[regexp,#].

    See: http://ruby-doc.org/core/String.html#method-i-5B-5D

    Note: str[regexp, capture] → new_str or nil

    0 讨论(0)
  • 2020-11-30 19:37

    Here's a slightly more flexible approach using the match method. With this, you can extract more than one string:

    s = "<ants> <pants>"
    matchdata = s.match(/<([^>]*)> <([^>]*)>/)
    
    # Use 'captures' to get an array of the captures
    matchdata.captures   # ["ants","pants"]
    
    # Or use raw indices
    matchdata[0]   # whole regex match: "<ants> <pants>"
    matchdata[1]   # first capture: "ants"
    matchdata[2]   # second capture: "pants"
    
    0 讨论(0)
  • 2020-11-30 19:46

    You can use a regular expression for that pretty easily…

    Allowing spaces around the word (but not keeping them):

    str.match(/< ?([^>]+) ?>\Z/)[1]
    

    Or without the spaces allowed:

    str.match(/<([^>]+)>\Z/)[1]
    
    0 讨论(0)
提交回复
热议问题