Reputation: 527
I have a sentence,
let message = "Hi thank you for #num#num bye"
Here in place of #num, there can be any values but atleast 1 and maximum 5 characters can be there. So here is how I'm replacing the #num like below.
Hi thank you for .{1,5}.{1,5} bye
So Im forming the regex like below,
let regex = /^Hi\s*thank\s*you\s*for\s*.{1,5}.{1,5} bye$/i
let usermsg = "Hi thankyou for 6 bye"
Ideally the above one should fail since I have substituted only one value. Minimium there should be 2 values.
but when I try to test using below,
console.log(regex.test(usermsg) ? "Pass" : "Fail", "==>", usermsg );
It is failing. Kindly help me on this.
Upvotes: 2
Views: 431
Reputation: 348
You are almost there. The only issue is that with \s*
after 'for' you allow zero or more space characters. So with your test message, the space in ' 6' is considered as 1 character part of the first .{1,5}
group.
Changing \s*
to \s+
will solve your problem.
+
matches one or more characters
Solution -
let regex = /^Hi\s*thank\s*you\s*for\s+.{1,5}.{1,5} bye$/i
Here is a nice tool to test your regex and debug - https://regex101.com/
Upvotes: 1