diff --git a/bootstrap/spec/std/string_spec.cr b/bootstrap/spec/std/string_spec.cr
index fdde92cbc86e46e1219678cd6860f2729a66ff41..681b5d2d2e97a2c68b0b11c3105fae4783eee118 100755
--- a/bootstrap/spec/std/string_spec.cr
+++ b/bootstrap/spec/std/string_spec.cr
@@ -180,4 +180,12 @@ describe "String" do
     assert { "foobar".ends_with?("foobarbaz").should be_false }
     assert { "foobar".ends_with?("xbar").should be_false }
   end
+
+  describe "=~" do
+    it "matches with group" do
+      "foobar" =~ /(o+)ba(r?)/
+      $1.should eq("oo")
+      $2.should eq("r")
+    end
+  end
 end
\ No newline at end of file
diff --git a/std/regexp.cr b/std/regexp.cr
index 667055e47553efe47b80ec4c36b9c7417e23cdd0..4e08b77a26d0a019c003cd1a369330693b138374 100644
--- a/std/regexp.cr
+++ b/std/regexp.cr
@@ -44,6 +44,8 @@ class Regexp
 end
 
 class MatchData
+  EMPTY = MatchData.new("", "", 0, Pointer(Int32).malloc(0))
+
   def initialize(regex, string, pos, ovector)
     @regex = regex
     @string = string
diff --git a/std/string.cr b/std/string.cr
index 57aaa0fd5d94afb390675b98ffaa4e8004eac2cb..5be2c63b29e1444d4e8378d842d5df7e942083db 100644
--- a/std/string.cr
+++ b/std/string.cr
@@ -176,8 +176,14 @@ class String
   end
 
   def =~(regex)
-    $~ = match = regex.match(self)
-    match ? match.begin(0) : nil
+    match = regex.match(self)
+    if match
+      $~ = match
+      match.begin(0)
+    else
+      $~ = MatchData::EMPTY
+      nil
+    end
   end
 
   def +(other)