0

given these strings:

a
b
ab
ba
bab
aba
abab
babab
asdgasdgsdgasa

I want the following output: true true false false true true false true true

I have this regex ^([ab])(?:.*?\1)?$

It matches well in this debugger: https://regex101.com/ However it doesn't match anything in this debugger: https://regexr.com/

Why is that?

Also why this gives true:

console.log(/^([ab])(?:.*?\1)?$/.test('aba'))
true

While the following gives false?

var re = new RegExp("^([ab])(?:.*?\1)?$");

re.test("aba");
false

My question is not to provide new ways or new regexps that match those strings. I just want to: 1) understand why there are such differences between regex debuggers 2) If the regex I gave is good to match such strings 3) Why the first console log matches, while the second does not and what should I change in order to make it work with re.test

Pikk
  • 2,343
  • 6
  • 25
  • 41

1 Answers1

3
  1. The first regex debugger has the multiline flag enabled by default; the second does not. If you enable the multiline (m) flag in the second one, it will work just like in the first.

  2. As ibrahim mahrir pointed out, you don't really need to use regex. You can just use str[0] === str[str.length - 1].

  3. In var re = new RegExp("^([ab])(?:.*?\1)?$");, you need to escape the backslash: "^([ab])(?:.*?\\1)?$"

Skylar
  • 928
  • 5
  • 18