Skip to content

Commit

Permalink
Fix regexps so they are anchored to start/end of string instead of st…
Browse files Browse the repository at this point in the history
…art/end of line
  • Loading branch information
timcraft committed Jan 20, 2013
1 parent 32cd677 commit 18c02e8
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
2 changes: 1 addition & 1 deletion lib/uk_phone_numbers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def self.pattern_to_regexp(pattern)
regexp = regexp.split.map { |p| "(#{p})" }.join
regexp.gsub!(/\[([^\]]*)\]/, '(?:\1)?')
regexp.gsub!(/#/, '\d')
Regexp.new("^#{regexp}$")

This comment has been minimized.

Copy link
@hinglau886

hinglau886 Jun 20, 2024

正則表達式。new(“\\A#{regexp}\\z”)

正則表達式。新(“\A#{regexp}\z”)

Regexp.new("\\A#{regexp}\\z")
end

REGEXPS = []
Expand Down
14 changes: 9 additions & 5 deletions spec/uk_phone_numbers_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,23 @@ def regexp_for(pattern)
end

it "strips parens from the pattern" do
regexp_for("()").should == "^$"
regexp_for("()").should_not include("()")
end

it "parenthesises whitespace-separated sections" do
regexp_for("0 12 345").should == "^(0)(12)(345)$"
regexp_for("0 12 345").should include("(0)(12)(345)")
end

it "replaces # with \\d" do
regexp_for("0#").should == "^(0\\d)$"
regexp_for("0#").should include("(0\\d)")
end

it "replaces bracketed expressions with optional non-capturing groups" do
regexp_for("0[12]3[4]5").should == "^(0(?:12)?3(?:4)?5)$"
regexp_for("0[12]3[4]5").should include("(0(?:12)?3(?:4)?5)")
end

it "handles hashes inside brackets" do
regexp_for("0[#]1[#]2").should == "^(0(?:\\d)?1(?:\\d)?2)$"
regexp_for("0[#]1[#]2").should include("(0(?:\\d)?1(?:\\d)?2)")
end
end

Expand All @@ -44,6 +44,10 @@ def regexp_for(pattern)
it "returns false for invalid numbers" do
subject.valid?('08456123123123').should be_false
end

it "returns false for multiline strings containing a valid number" do
subject.valid?("08456123123\nnotaphonenumber\n").should be_false
end
end

describe ".format" do
Expand Down

0 comments on commit 18c02e8

Please sign in to comment.