Sha256: 2243bc648106ab9cce3084267076b4ca16301a6b7b60bfda1e896a7b5f21aeab

Contents?: true

Size: 1.96 KB

Versions: 10

Compression:

Stored size: 1.96 KB

Contents

# TITLE:
#
#   String Scan-like Extensions
#
# SUMMARY:
#
#   Extensions providing alternate methods akin to scanning.
#
# CREDIT:
#
#   - Thomas Sawyer

#
class String

  # Breaks a string up into an array based on a regular expression.
  # Similar to scan, but includes the matches.
  #
  #   s = "<p>This<b>is</b>a test.</p>"
  #   s.divide( /\<.*?\>/ )
  #
  # _produces_
  #
  #   ["<p>This", "<b>is", "</b>a test.", "</p>"]
  #
  def divide( re )
    re2 = /#{re}.*?(?=#{re}|\Z)/
    scan(re2) #{re}(?=#{re})/)
  end

  # Like #scan but returns MatchData ($~) rather
  # then matched string ($&).
  #
  def mscan(re) #:yield:
    if block_given?
      scan(re) { yield($~) }
    else
      m = []
      scan(re) { m << $~ }
      m
    end
  end

  # Breaks a string up into an array based on a regular expression.
  # Similar to scan, but includes the matches.
  #
  #   s = "<p>This<b>is</b>a test.</p>"
  #   s.shatter( /\<.*?\>/ )
  #
  # _produces_
  #
  #   ["<p>", "This", "<b>", "is", "</b>", "a test.", "</p>"]
  #
  def shatter( re )
    r = self.gsub( re ){ |s| "\1" + s + "\1" }
    while r[0,1] == "\1" ; r[0] = '' ; end
    while r[-1,1] == "\1" ; r[-1] = '' ; end
    r.split("\1")
  end

end


#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TestStringScan < Test::Unit::TestCase

    def test_mscan
      r = 'abc,def,gh'.mscan(/[,]/)
      assert( r.all?{ |md| MatchData === md } )
      assert_equal( 2, r.to_a.length )
      assert_equal( ',', r[0][0] )
      assert_equal( ',', r[1][0] )
    end

    def test_divide
      s = "<p>This<b>is</b>a test.</p>"
      d = s.divide( /<.*?>/ )
      e = ["<p>This", "<b>is", "</b>a test.", "</p>"]
      assert_equal(e, d)
    end

    def test_shatter
      s = "<p>This<b>is</b>a test.</p>"
      sh = s.shatter( /<.*?>/ )
      e = ["<p>", "This", "<b>", "is", "</b>", "a test.", "</p>"]
      assert_equal(e, sh)
    end

  end

=end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
facets-2.0.0 lib/core/facets/string/scan.rb
facets-2.0.1 lib/core/facets/string/scan.rb
facets-2.0.2 lib/core/facets/string/scan.rb
facets-2.0.5 lib/core/facets/string/scan.rb
facets-2.1.0 lib/core/facets/string/scan.rb
facets-2.1.1 lib/core/facets/string/scan.rb
facets-2.1.2 lib/core/facets/string/scan.rb
facets-2.0.3 lib/core/facets/string/scan.rb
facets-2.0.4 lib/core/facets/string/scan.rb
facets-2.1.3 lib/core/facets/string/scan.rb