Home > Blockchain >  Matching string which has *, 0-9 and # at the end
Matching string which has *, 0-9 and # at the end

Time:05-19

The title pretty much says it.

  1. * is required as the first element
  2. Up to 16 digits allowed after that
  3. Last element always has to be #

Overall string length should be more than 18 items.

Regex that I have now:

[*][0-9]{0,16}[#]

But this still matches *#

CodePudding user response:

You seem to have a fundamental misunderstanding of what the {0,16} quantifier does in this scenario - the 0 value it will make the character class you're applying to effectively optional.

Removing the unnecessary character classes and replacing them with proper escapes, you're probably looking for something more like:

\*\d{1,16}\#

const pattern = /\*\d{1,16}\#/;
console.log(pattern.test("*#")); // should be false
console.log(pattern.test("*1#")); // should be true
console.log(pattern.test("*1234567890123456#")); // should be true
console.log(pattern.test("*12345678901234567#")); // should be false
console.log(pattern.test("*1234567890123456")); // should be false
console.log(pattern.test("1234567890123456#")); // should be false

  • Related