Error:

Simple pattern matching

s = 'foo bar foo'
if (s =~ /foo/) then
  puts "contains foo"
end

Case-insensitive pattern matching

s = 'Foo bar Foo'
if (s =~ /foo/i) then
  puts "contains foo"
end

Simple pattern substitution

s = 'Foo bar Foo'
s.sub!(/foo/i, 'none')
s # => "none bar Foo"

s = 'Foo bar Foo'
s.gsub!(/foo/i, 'none')
s # => "none bar none"

Match if X is followed by Y

sOk = 'string foobar'
sNotOk = 'string fooNOTbar'
sOk =~ /foo(?=bar)/    # => 7
sNotOk =~ /foo(?=bar)/ # => nil

Match if X is not followed by Y

sNotOk = 'string foobar'
sOk = 'string fooNOTbar'
sOk =~ /foo(?!bar)/    # => 7
sNotOk =~ /foo(?!bar)/ # => nil

Do not remember the match

r = /foo(?:bar){1,2}/
r.match("foobar") # => #<MatchData "foobar">

r = /foo(bar){1,2}/
r.match("foobar") # => #<MatchData "foobar" 1:"bar">

Swap words

s = 'John Smith'
s.sub!(/(\w+)\s+(\w+)/, '\2, \1') # => "Smith, John"

Access matched string (capture groups)

s = 'Smith, John'
match_data = /(\w+),\s+(\w+)/.match(s)
match_data[1] # => "Smith"
match_data[2] # => "John"

Used matched string in substitution

s = 'John Smith'
s.sub!(/(\w+)\s+(\w+)/, '\2, \1') # => "Smith, John"

Finding the Nth occurrence of a match

s = "six one four seven seven eight"
idx = 0
s.gsub!(/\w+/) do |word|
    idx += 1
    if idx == 3 then
        "---"
    else
        word
    end
end
# => "six one --- seven seven eight"

Matching multiple lines

s = "foo\nline 2\nbar"
/foo.*bar/.match(s)  # => nil
/foo.*bar/m.match(s) # => #<MatchData "foo\nline 2\nbar">

Greedy and non-greedy matches

s = 'foobarbar'
# Greedy
/foo.*bar/.match(s) # => #<MatchData "foobarbar">
# Non-greedy
/foo.*?bar/.match(s) # => #<MatchData "foobar">

AND, OR and NOT matches

regexp_foo_or_bar = /foo|bar/
regexp_foo_and_bar = /(?=.*foo)(?=.*bar)/
regexp_foo_and_not_bar = /(?=.*foo)(?=.*bar)/