-2

I would like to check if my regex is true. So this is what I have tried:

const a = new RegExp(`(?<=TITLE.+prefix=)[^\]|\|]+`);

That returns true, which is correct:

console.log(a.test('[TITLE|prefix=bss|suffix=a] [STORENAME] [DYNAMIC|limit=10|seperator=-|random=1|reverse=1]'));

That one returns true but it shouldn't:

console.log(a.test('[ANYTHING|somethingelse=bss|suffix=a] [STORENAME] [DYNAMIC|limit=10|seperator=-|random=1|reverse=1]'));

See here the result:

const a = new RegExp(`(?<=TITLE.+prefix=)[^\]|\|]+`);
console.log(a.test('[TITLE|prefix=bss|suffix=a] [STORENAME] [DYNAMIC|limit=10|seperator=-|random=1|reverse=1]'));
console.log(a.test('[ANYTHING|somethingelse=bss|suffix=a] [STORENAME] [DYNAMIC|limit=10|seperator=-|random=1|reverse=1]'));
ihimv
  • 1,308
  • 12
  • 25
Proseller
  • 113
  • 1
  • 8

1 Answers1

-1

If you create your REGEX with the constructor, i.e. as a string, you need to double-escape backslashes, so:

new RegExp(`(?<=TITLE.+prefix=)[^\\]|\\|]+`)

Also note that |\| is unnecessary; should be just |. Inside a range, the pipe character does not have special relevance so it will be matched literally.

Mitya
  • 33,629
  • 9
  • 60
  • 107
  • 1
    Why do you (a user who should know the rules) add an answer to a duplicate (which has already been closed as such)? – Andreas Oct 27 '20 at 11:55
  • @Andreas Yes, I concede the point. I normally never do this; I'm not really sure why this one didn't immediately strike me as having a likely duplicate. Speaking of rules, you will know, though, that this is not, in itself, grounds for downvoting. Voting should pertain only to the quality of the answer. – Mitya Oct 27 '20 at 14:06