Manzer A
Manzer A

Reputation: 3806

Regex test() method returning false for a valid regex having match

When pattern is being tested in https://regex101.com/r/YbRw2h/1, it is displaying two matches.

var patt = /\{panel:bgColor=#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})}(\r\n|\r|\n)?(.*?){panel}/gm

var str = `{panel:bgColor=#deebff}\nThis is info panel\n{panel}fkjfkfwkwfj\
    
                 {panel:bgColor=#deebff}\nThis is info panel\n{panel}`


console.log(patt.test(str)) //false

How to fix regex?

Upvotes: 1

Views: 73

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

You could use:

{panel:bgColor=#(?:[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})}[^]*?{panel}

Explanation

  • {panel:bgColor=# Match literally
  • (?: Non capture group for the alternation
    • [A-Fa-f0-9]{6} Match 6 occurrences of A-F a-f or a digit 0-9
    • | Or
    • [A-Fa-f0-9]{3} Match 3 occurrences of A-F a-f or a digit 0-9
  • ) Close non capture group
  • } Match literally
  • [^]*? Match any char including newlines non greedy
  • {panel} Match literally

Regex demo

Upvotes: 1

Related Questions