ruby regex: match and get position(s) of

后端 未结 3 472
暖寄归人
暖寄归人 2020-12-03 01:00

I\'d like to match a regex and get the position in the string of the match

For example,

\"AustinTexasDallasTexas\".match_with_posn /(Texas)/
<         


        
相关标签:
3条回答
  • 2020-12-03 01:29

    Sort of, see String#index

    "AustinTexasDallasTexas".index /Texas/
    => 6
    

    Now, you could extend the String API.

    class String
      def indices e
        start, result = -1, []
        result << start while start = (self.index e, start + 1)
        result
      end
    end
    p "AustinTexasDallasTexas".indices /Texas/
    => [6, 17]
    
    0 讨论(0)
  • 2020-12-03 01:44

    Using Ruby 1.8.6+, you can do this:

    require 'enumerator' #Only for 1.8.6, newer versions should not need this.
    
    s = "AustinTexasDallasTexas"
    positions = s.enum_for(:scan, /Texas/).map { Regexp.last_match.begin(0) }
    

    This will create an array with:

    => [6, 17]
    
    0 讨论(0)
  • 2020-12-03 01:45
    "AustinTexasDallasTexas".gsub(/Texas/).map { Regexp.last_match.begin(0) }
      #=> [6, 17]
    
    0 讨论(0)
提交回复
热议问题