Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Documentation of Regex.new #3155

Closed
drosehn opened this issue Aug 14, 2016 · 1 comment
Closed

Documentation of Regex.new #3155

drosehn opened this issue Aug 14, 2016 · 1 comment

Comments

@drosehn
Copy link

drosehn commented Aug 14, 2016

The documentation for Regex.new at Regex.html has the line:

Regex.new("^a-z+:\s+\w+")                     # => /^a-z+:\s+\w+/

As does the source code for Regex.initialize in src/regex.cr

That is not correct, because the parsing of string values is not the same as the parsing of Regex values, particularly when it comes to escaped characters like \d.

dumb_rx = Regex.new( "\s+\d+\s+" )
if "aa 22 cc" =~ dumb_rx
  printf "single-slash Match\n"
else
  printf "single-slash No Match\n"
end

dumb_rx = Regex.new( "\\s+\\d+\\s+" )
if "aa 22 cc" =~ dumb_rx
  printf "double-slash Match\n"
else
  printf "double-slash No Match\n"
end

produces:

single-slash No Match
double-slash Match

(which is what I would expect it to do, of course).

@drosehn
Copy link
Author

drosehn commented Aug 14, 2016

Also, in Ruby one can use a regexp-value as the first parameter to Regexp.new(), to avoid the extra level of escaping that you'd need when using a string-value for that parameter. Crystal does not allow that, although I do not know if that was intentional. If the user tries:

dumb_rx = Regex.new( /\s+\d+\s+/ )
if "aa 22 cc" =~ dumb_rx
  printf "single-slash Match\n"
else
  printf "single-slash No Match\n"
end

they get the compile-time error of:

Error in line 1: instantiating 'Regex:Class#new(Regex)'

instantiating 'Regex#initialize(Regex)'

in /usr/lib/crystal/regex.cr:224: undefined method 'gsub' for Regex

    source = source.gsub('\u{0}', "\\0")
                    ^~~~

================================================================================

Regex trace:

  /usr/lib/crystal/regex.cr:222

      def initialize(source, @options : Options = Options::None)

You might wonder why anyone would bother doing Regexp.new( /patrn/ ) instead of simply using /patrn/, and I must admit I do not know why I started doing that. Maybe it had something to do with the state of ruby back in 2002. But if crystal does intend to not allow that, then maybe the definition for Regex.initialize should be:

def initialize(source : String, @options : Options = Options::None)

instead of:

def initialize(source, @options : Options = Options::None)

?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants