Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions mrbgems/mruby-regexp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ simulation) with backtracking fallback.
re = Regexp.new("pattern", Regexp::IGNORECASE)
re = /pattern/i # literal syntax
re.match("string") # => MatchData or nil
re.match("string") { |md| ... } # => block result, or nil if no match
re.match?("string") # => true/false
re =~ "string" # => index or nil
re === "string" # => true/false (for case/when)
Expand All @@ -71,6 +72,7 @@ md.named_captures # => {"name" => "value", ...}

# String methods
str.match(re) # => MatchData or nil
str.match(re) { |md| ... } # => block result, or nil if no match
str.match?(re) # => true/false
str =~ re # => index or nil
str.sub(re, replacement) # replace first occurrence
Expand Down
4 changes: 2 additions & 2 deletions mrbgems/mruby-regexp/mrblib/string_regexp.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ class String
# back to the core implementation.
alias __split split

def match(re, pos = 0)
def match(re, pos = 0, &block)
re = Regexp.new(re) if re.is_a?(String)
re.match(self, pos)
re.match(self, pos, &block)
end

def match?(re, pos = 0)
Expand Down
30 changes: 30 additions & 0 deletions mrbgems/mruby-regexp/test/regexp.rb
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,36 @@
assert_equal "world", md[2]
end

assert("String#match - block") do
assert_equal "L", "hello".match(Regexp.new("l")) { |md| md[0].upcase }
assert_equal "ll", "hello".match("l+") { |md| md[0] }

called = false
assert_nil("hello".match(Regexp.new("z")) { called = true })
assert_false called

called = false
assert_nil("hello".match(Regexp.new("l"), 4) { called = true })
assert_false called

called = false
result = "hello".match("l+") do
called = true
nil
end
assert_nil result
assert_true called
end
Comment thread
coderabbitai[bot] marked this conversation as resolved.

assert("String#match - break out of the block") do
assert_equal :broke, "hello".match("l+") { break :broke }
end

assert("String#match - block sees the match globals") do
assert_equal "ll", "hello".match("l+") { $~[0] }
assert_equal "ll", "hello".match("l+") { Regexp.last_match(0) }
end

assert("String#=~") do
assert_equal 1, "abc" =~ Regexp.new("b")
assert_nil "abc" =~ Regexp.new("z")
Expand Down
Loading