From b6bd2dca95e5aec623a688c6ef7d71ccd1b62b51 Mon Sep 17 00:00:00 2001 From: TSUYUSATO Kitsune Date: Sat, 30 Dec 2017 22:11:57 +0900 Subject: [PATCH 1/2] Work String#starts_with? with regex This feature is imported from Ruby 2.5.0. See: https://bugs.ruby-lang.org/issues/13712 --- spec/std/string_spec.cr | 2 ++ src/string.cr | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/spec/std/string_spec.cr b/spec/std/string_spec.cr index ddf4bdabd67d..330a7760848b 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 } diff --git a/src/string.cr b/src/string.cr index 14f9ecf4f68d..08bdafd33d63 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 From 8432c14d89abe1719dfcf064e46e43be316bb806 Mon Sep 17 00:00:00 2001 From: TSUYUSATO Kitsune Date: Tue, 2 Jan 2018 10:08:23 +0900 Subject: [PATCH 2/2] Fix String#ends_with to accept regex See: https://github.com/crystal-lang/crystal/pull/5485#issuecomment-354667698 --- spec/std/string_spec.cr | 2 ++ src/string.cr | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/spec/std/string_spec.cr b/spec/std/string_spec.cr index 330a7760848b..409413a5635b 100644 --- a/spec/std/string_spec.cr +++ b/spec/std/string_spec.cr @@ -938,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 08bdafd33d63..ad95f6957a37 100644 --- a/src/string.cr +++ b/src/string.cr @@ -3995,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`. # # ```