From 4f4240b1c2bdb44c24395483567a4a6ce667f540 Mon Sep 17 00:00:00 2001 From: TSUYUSATO Kitsune Date: Mon, 9 Apr 2018 19:07:03 +0900 Subject: [PATCH] Work String#starts_with? with regex (#5485) * Work String#starts_with? with regex This feature is imported from Ruby 2.5.0. See: https://bugs.ruby-lang.org/issues/13712 * Fix String#ends_with to accept regex See: https://github.com/crystal-lang/crystal/pull/5485#issuecomment-354667698 --- spec/std/string_spec.cr | 4 ++++ src/string.cr | 8 ++++++++ 2 files changed, 12 insertions(+) diff --git a/spec/std/string_spec.cr b/spec/std/string_spec.cr index 13a07e03148f..916024d73aed 100644 --- a/spec/std/string_spec.cr +++ b/spec/std/string_spec.cr @@ -945,6 +945,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 } @@ -956,6 +958,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 84712fa1353a..1260a0753c39 100644 --- a/src/string.cr +++ b/src/string.cr @@ -4020,6 +4020,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 @@ -4042,6 +4046,10 @@ class String true end + def ends_with?(re : Regex) + !!($~ = /#{re}\z/.match(self)) + end + # Interpolates *other* into the string using `Kernel#sprintf`. # # ```