-1

I have a regex with some named groups, that matches fine when I test it but not as part of my running app. In the code below the regex.exec will return null in my app environment, but matches everywhere else.

/^(goto|gt) (?<roomName>.*)/gim

when I test this regex in a node terminal:

> /^(goto|gt) (?<roomName>.*)/gim.exec('goto cell')
[
  'goto cell',
  'goto',
  'cell',
  index: 0,
  input: 'goto cell',
  groups: [Object: null prototype] { roomName: 'cell' }
]
>

I get a happy match. parsed has a value

Now when I run the same code in the app, here seen in the debugger, regex.test will work but regex.exec() won't yield any results. parsed is null

In this SO snipper engine there seems to be another issue stripping out the matching groups but this works locally for me at least the match.

Any other ideas why this behavior is being flaky? The environments, node versions etc. are all the same I'm running under. It is typescript but I checked the transpiled code and it's the same.

const RouterService = {
  goto () { console.log('do something') }
}

const input = 'goto cell'

const rule = {
  cname: 'goto',
  rex: /^(goto|gt) (?<roomName>.*)/gim,
  event: RouterService.goto,
  type: 'command'
}

if (rule) {
  const parsed = rule.rex.exec(input)
  console.log('input', input)
  console.log('rule', rule)
  console.log('parsed', parsed)
  parsed.groups = { ...parsed.groups }  // Object null prototype
  const parserResult = {
    parsed, rule
  }
  console.log('parserResult', parserResult)
}

in SO engine parsed has a value

but logging my app parsed is null

console log

app debugger: parsed is null

debugger

and here's the same code on repl.it, a bit closer than the SO engine.

https://repl.it/@dcsan/ChiefAggravatingAlphatest parsed has a value

snippet run from a terminal

Ahh regex. Now I have two problems.

dcsan
  • 11,333
  • 15
  • 77
  • 118

1 Answers1

3

Ref: RegExp.exec() returns NULL sporadically

Since you are using the g flag. After matching and returning the result, the regex will continue from where it stopped on the previous run. So, if you use g flag, you need to reset the regex to work properly.

That is why in your example first run gave you result and the second run gave you a null.

  • that's exactly what it is! Thanks! this was a real heisenbug to me. I didn't realize regexes had their own internal lifecycle like that ¯\_(ツ)_/¯ – dcsan Jul 24 '20 at 09:07