0

I have this regular expression /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi for testing a URL but it seems nondeterministic. How is this possible?

enter image description here

Flo
  • 65
  • 1
  • 9
  • I got it from [here](https://stackoverflow.com/a/3809435/8466696) – Flo Jul 12 '22 at 07:18
  • 1
    See [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test), section "Using test() on a regex with the "global" flag" – bui Jul 12 '22 at 07:21
  • 1
    This has been answered [time](https://stackoverflow.com/questions/2851308/why-does-my-javascript-regex-test-give-alternating-results) and [time](https://stackoverflow.com/questions/2630418/javascript-regex-returning-true-then-false-then-true-etc) and [time again](https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results). Please search before asking. Some of these questions probably popped up while you were typing your question. See the [how to ask](https://stackoverflow.com/help/how-to-ask) section before asking to get the most out of StackOverflow. – Adrian Wiik Jul 12 '22 at 07:23
  • @AdrianWiik Try posting this yourself. None of your posts came up as suggested. – Flo Jul 12 '22 at 08:03

2 Answers2

2

Your regex is searching for next match. The index where it stopped is stored in urlRegExp.lastIndex

1

Because there's a g flag.

So it will store lastIndex and wait for the next test.

What is RegExp.test:

JavaScript RegExp objects are stateful when they have the global or sticky flags set (e.g., /foo/g or /foo/y). They store a lastIndex from the previous match.

Chang Alex
  • 505
  • 3
  • 11