简体   繁体   English

正则表达式允许长度限制为 5 的所有字符?

[英]Regex to allow all characters with the length limit of 5?

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.这里可以有任何值来代替 #num,但至少可以有 1 个字符,最多可以有 5 个字符。 So here is how I'm replacing the #num like below.所以这就是我如何替换 #num 如下所示。

  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.至少应该有 2 个值。

but when I try to test using below,但是当我尝试使用下面的测试时,

  console.log(regex.test(usermsg) ? "Pass" : "Fail", "==>", usermsg );

It is failing.它失败了。 Kindly help me on this.请帮助我。

You are almost there.你快到了。 The only issue is that with \s* after 'for' you allow zero or more space characters.唯一的问题是在“for”之后使用\s*您允许零个或多个空格字符。 So with your test message, the space in ' 6' is considered as 1 character part of the first .{1,5} group.因此,对于您的测试消息,“6”中的空格被视为第一个.{1,5}组的 1 个字符部分。

Changing \s* to \s+ will solve your problem.\s*更改为\s+将解决您的问题。
+ 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/这是一个很好的工具来测试你的正则表达式和调试 - https://regex101.com/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM