Ruby/String/gsub

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

"FOO bar".gsub(/foo/i, "The bar").gsub(/bar/m, "result")

puts "FOO bar".gsub(/foo/i, "The bar").gsub(/bar/m, "result")



gsub alll with all

"That"s alll folks".gsub "alll", "all" # => "That"s all folks"



gsub does multiple substitutions at once

puts "this is a test".gsub("i", "")



gsub(/[^\d]+/, "").split(//)

numbers = "5276 4400 6542 1319".gsub(/[^\d]+/, "").split(//)
# =>    ["5", "2", "7", "6", "4", "4", "0", "0",
# =>     "6", "5", "4", "2", "1", "3", "1", "9"]



gsub lll with ll

"That"s alll folks".gsub "lll", "ll" # => "That"s all folks"



gsub method that performs a global substitution (like a search and replace) upon the string

"this is a test".gsub(/t/, "X")



gsub (or gsub!) replaces a substring (first argument) with a replacement string (second argument)

puts "That"s alll folks".gsub "alll", "all"



"Here is number #123".gsub(/[a-z]/i, "#").gsub(/#/, "P")

puts "Here is number #123".gsub(/[a-z]/i, "#").gsub(/#/, "P")



Normalize Ruby source code by replacing tabs with spaces

myString = "asdf\tasdf"
myString.gsub("\t", "  ")



Splitting Text into Sentences

class String
  def sentences
    gsub(/\n|\r/, " ").split(/\.\s*/)
  end
end
%q{Hello. This is a test of
basic sentence splitting. It
even works over multiple lines.}.sentences



Testing Sentence Separation

require "test/unit"
 
class String
  def sentences
    gsub(/\n|\r/, " ").split(/\.\s*/)
  end
end
def test_sentences
  assert_equal(["a", "b", "c d", "e f g"], "a. b. c d. e f g.".sentences)
  test_text = %q{Hello. This is a test
of sentence separation. This is the end
of the test.}
  assert_equal("This is the end of the test", test_text.sentences[2])
end



Transform Windows-style newlines to Unix-style newlines

"Line one\n\rLine two\n\r".gsub("\n\r", "\n")
# => "Line one\nLine two\n"
#Transform all runs of whitespace into a single space character
"\n\rThis string\t\t\tuses\n all\tsorts\nof whitespace.".gsub(/\s+/, " ")
# => " This string uses all sorts of whitespace."



use gsub to eradicate the spaces from text string

lines = File.readlines("text.txt")
line_count = lines.size
text = lines.join
puts "#{line_count} lines"
total_characters_nospaces = text.gsub(/\s+/, "").length
puts "#{total_characters_nospaces} characters excluding spaces"



Use whitespace as the place holder

" \bIt"s whitespace, Jim,\vbut not as we know it.\n".gsub(/[\s\b\v]+/, " ")
# => " It"s whitespace, Jim, but not as we know it. "