Reputation: 461
In vanilla Javascript I want to check a string.
const myRegex = /^\d+|#\d+/g;
console.log(`${myRegex.test("3#123#432#555")}`); // pattern is ok -> true
console.log(`${myRegex.test("3#123#432##555")}`); // two ## -> patter wrog -> but result is true (would like this to be false)
console.log(`${myRegex.test("3#123#432#55a5")}`); // a character in the string -> pattern wrong -> but result is true (should also be false)
I played around in https://regex101.com/r/tI1sOa/1/ I get a perfect match using this regex but I want it to return false when the pattern is altered.
Pattern definition should be: number#number#number#number#number (so first we have a number followed by #number, as many times as I want)
If the pattern is number### or #number or numberLetter#number or any other combination that does not respect the pattern should return false for the test.
How can I check this with regex? Why is the one I came up with not working as I expect it?
Thank you!
Upvotes: 0
Views: 47
Reputation: 816324
^\d+|#\d+
means
#
followed by one or more digits anywhere in the string.In other words, the ^
is part of the first alternative, it doesn't apply to second one.
A pattern that fulfills your requirements would be:
^\d+(#\d+)+$
#
followed by one or more digits, till the end of the stringUpvotes: 3