diff --git a/spec/std/string_spec.cr b/spec/std/string_spec.cr index ddf4bdabd67d..409413a5635b 100644 --- a/spec/std/string_spec.cr +++ b/spec/std/string_spec.cr @@ -925,6 +925,8 @@ describe "String" do it { "foobar".starts_with?("").should be_true } it { "foobar".starts_with?("foobarbaz").should be_false } it { "foobar".starts_with?("foox").should be_false } + it { "foobar".starts_with?(/foo/).should be_true } + it { "foobar".starts_with?(/bar/).should be_false } it { "foobar".starts_with?('f').should be_true } it { "foobar".starts_with?('g').should be_false } it { "よし".starts_with?('よ').should be_true } @@ -936,6 +938,8 @@ describe "String" do it { "foobar".ends_with?("").should be_true } it { "foobar".ends_with?("foobarbaz").should be_false } it { "foobar".ends_with?("xbar").should be_false } + it { "foobar".ends_with?(/bar/).should be_true } + it { "foobar".ends_with?(/foo|baz/).should be_false } it { "foobar".ends_with?('r').should be_true } it { "foobar".ends_with?('x').should be_false } it { "よし".ends_with?('し').should be_true } diff --git a/src/string.cr b/src/string.cr index 14f9ecf4f68d..ad95f6957a37 100644 --- a/src/string.cr +++ b/src/string.cr @@ -3969,6 +3969,10 @@ class String false end + def starts_with?(re : Regex) + !!($~ = re.match_at_byte_index(self, 0, Regex::Options::ANCHORED)) + end + def ends_with?(str : String) return false if str.bytesize > bytesize (to_unsafe + bytesize - str.bytesize).memcmp(str.to_unsafe, str.bytesize) == 0 @@ -3991,6 +3995,10 @@ class String true end + def ends_with?(re : Regex) + !!($~ = /#{re}\z/.match(self)) + end + # Interpolates *other* into the string using `Kernel#sprintf`. # # ```