3

The simplest way to express this question is with a small example in the repl:

coffee> "hello".split(/: #/) #this is fine
[ 'hello' ]
coffee> "hello".split(/\s#/) #all good here too
[ 'hello' ]
coffee> "hello".split(/ #/)  #wtf??
[stdin]:1:20: error: missing )
"hello".split(/ #/)

Why does the last regex not work? from playing around a bit it seems that there will be an error for any regex matching ^ +.*#.*$ Note, that is a space at the start of the regex. (e.g. / foo#bar/ but not /foo bar#baz/).

Is this a bug in the parser?

(running CoffeeScript version 1.7.1 on Arch Linux)

Mike H-R
  • 7,726
  • 5
  • 43
  • 65

1 Answers1

4

Because the coffee lexer is trying to figure out if the first / is the division operator or a start of a regex, and guesses wrong in that case. Here is the relevant code. I am not sure if that is a bug.

If you put that in a file:

"hallo".match / #/
  1

and use coffee -p you'll see that it is parsed as the division operator. If you add an non-capturing group at the beginning, you'll get an Expression that is (almost, since it does take up more space and neglegible regex-compilation time) equivalent to the one you're aiming for:

"hall #o".match /(?:) #/

Edit:

As mu is to short has pointed out, it might be easier to just put a backslash in front of the space.

"hall #o".match /\ #/
Community
  • 1
  • 1
Patrick J. S.
  • 2,885
  • 19
  • 26
  • 1
    I'd probably go with `/\ #/`, backslash is the usual [do what I want kludge](http://stackoverflow.com/a/9492992/479863). – mu is too short Oct 04 '14 at 18:12
  • 1
    Ahhh, I had been trying to do `/ \#/` to try and get it to work (which doesn't). Good point about escaping the space instead. Do we think that it's a bug? Should I be opening an issue on github? Thanks again. – Mike H-R Oct 05 '14 at 02:04
  • 1
    can you star issues on github? I just searched for it – [it exists as an issue since March](https://github.com/jashkenas/coffeescript/issues/3410). – Patrick J. S. Oct 05 '14 at 02:24