0

I have this code in javascript and I don't understand why last 2 test is true

    let regIndir=new RegExp(/([0-9Ii??????-?À-ž?a-zA-Z\- '/.,()#:])*/,'g');
    regIndir.test("carmine") --> true ok
    regIndir.test("carmine _") --> true ????why??
    regIndir.test("carmine §") --> true ????why??

Rahman Haroon
  • 1,088
  • 2
  • 12
  • 36
carminePat
  • 159
  • 2
  • 5
  • 13
  • What are you trying to do? – Unmitigated Dec 03 '20 at 15:21
  • 1
    Why not? You've not constrained your regex, so it only tests if the string *contains* at least t one valid character. Also, since you've put a `*` an empty string is *also* valid, therefore *any* string is valid. See [Match exact string](https://stackoverflow.com/q/6298566) – VLAZ Dec 03 '20 at 15:22
  • The lack of anchors is the biggest problem. Although [the global flag can also cause problems](https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results) – VLAZ Dec 03 '20 at 15:23
  • if I test regEx and test in online tester (regexr.com) first is valid and last 2, no – carminePat Dec 03 '20 at 15:24
  • @carminePat [it definitely produces a match in JS here](https://regex101.com/r/Fjl5UV/1) – VLAZ Dec 03 '20 at 15:25
  • if remove global flag nothing change, results are some – carminePat Dec 03 '20 at 15:25
  • Your regex matches anything since the pattern is `*`-quantified, that is why. Use anchors – Wiktor Stribiżew Dec 03 '20 at 15:32
  • @VLAZ in online tester character "_" or character "§" is not allowed, why test not return false? – carminePat Dec 03 '20 at 15:33
  • @carminePat that's *not* what you're testing for. See the linked dupe. If the regex finds *any* match *anywhere* in the string, then `.test()` returns `true`. In `carmine _` the portion "carmine " matches, therefore `.test()` is `true`. Again, since you also have `*` quantifier, then *any* string would match because any string contains the empty string. Even `_` by itself would test `true`. – VLAZ Dec 03 '20 at 15:36
  • @VLAZ ok! do you have suggest for solution to valid all String or nothing? – carminePat Dec 03 '20 at 15:40
  • Yes: [Match exact string](https://stackoverflow.com/q/6298566) – VLAZ Dec 03 '20 at 15:40
  • @VLAZ thank you very much, your solution is just for my question, you have a good day, thank you – carminePat Dec 03 '20 at 15:45

0 Answers0