regular_expressions_2.sf 496 B

12345678910111213141516171819
  1. #!/usr/bin/ruby
  2. #
  3. ## https://rosettacode.org/wiki/Regular_expressions
  4. #
  5. var str = "I am a string";
  6.  
  7. # Substitute something mached by a regex
  8. str.sub!(/ a /, ' another '); # "I am a string" => "I am another string"
  9.  
  10. # Remove something matched by a regex
  11. str -= / \Kanother /i; # "I am another string" => "I am string"
  12.  
  13. # Global subtitution with a block
  14. str = str.gsub(/(\w+)/, {|s1| 'x' * s1.len}); # globaly replace any word with 'xxx'
  15.  
  16. say str; # prints: 'x xx xxxxxx'