Skip to content

Commit

Permalink
Fix loading/parsing regular expressions
Browse files Browse the repository at this point in the history
This fixes the issue where regular expression would come back slightly
different after going through a YAML load/dump cycle. Because we're used
to having to escape forward slashes in regular expression literals
(because the literal is delimited by slashes), but the deserializer
takes the literal output from `Regexp#inspect` and feeds it as a string
into `Regexp.new`, which expects a string, not a Regexp literal, cycling
did not properly work before this commit.

I've also changed the code to be a bit more readable, I hope this
doesn't affect performance.
  • Loading branch information
mamhoff committed Feb 4, 2025
1 parent 5605134 commit f4dd8da
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
6 changes: 3 additions & 3 deletions lib/psych/visitors/to_ruby.rb
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,11 @@ def deserialize o
Float(@ss.tokenize(o.value))
when "!ruby/regexp"
klass = class_loader.regexp
o.value =~ /^\/(.*)\/([mixn]*)$/m
source = $1
matches = /^\/(?<string>.*)\/(?<options>[mixn]*)$/m.match(o.value)
source = matches[:string].gsub('\/', '/')
options = 0
lang = nil
$2&.each_char do |option|
matches[:options].each_char do |option|
case option
when 'x' then options |= Regexp::EXTENDED
when 'i' then options |= Regexp::IGNORECASE
Expand Down
4 changes: 4 additions & 0 deletions test/psych/test_yaml.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ def test_multiline_regexp
assert_cycle(Regexp.new("foo\nbar"))
end

def test_regexp_with_slash
assert_cycle(Regexp.new('/'))
end

# [ruby-core:34969]
def test_regexp_with_n
assert_cycle(Regexp.new('',Regexp::NOENCODING))
Expand Down

0 comments on commit f4dd8da

Please sign in to comment.