Crystal not use same Regex engine as Ruby?

Following method failed because \k<INDEX> is not valid for Crystal, but it works with Ruby.

def first_non_repeating_char_1(str)
  # Use a Regex negative look-ahead assertion to find the position
  # where the next char is different with current char, do it twice.
  idx = /(.)(?!a)(.)(?!b)/i =~ str
  str[idx + 1]
end

str = 'aaabbbccrdddeeefdddccceeeaaakfffl'
assert_equal 'r', first_non_repeating_char_1(str)
 19 | idx = /(.)(?!\k<-1>)(.)(?!\k<-1>)/i =~ str
            ^
Error: invalid regex: subpattern name expected at 9

Why Crystal not support it? any alternative?

1 Like

Crystal Regex uses the PCRE engine while Ruby uses Onigmo. You’d have rework the regex to be PCRE compliant. https://regexr.com/ can help with this, just be sure to select PCRE version and not Javascript as it defaults to.

Related: Upgrade `Regex` engine · Issue #11331 · crystal-lang/crystal · GitHub

3 Likes

I thought Onigoma is some engine number used by PCRE … :joy: