[英]How to combine regex in JavaScript
我有一个要求,其中输入字符串不应为空字符串(允许所有字符),长度应在1到500之间。
我分别找到了工作表达式,一个用于检查空字符串,另一个用于长度。 我无法将它们合并成一个表达式,该表达式应该告诉我输入是否为“空字符串”或超过500个字符。
用于空字符串
var regex = /^\s*$/;
长度
{1,499}
从检查“空”字符串的示例中可以明显看出,您想忽略开头或结尾的空格。
如果您实际上没有正则表达式要求,最简单的方法是trim
并检查长度:
str = str.trim();
if (str.length && str.length <= 500) {
// All good
}
但是,如果您需要一个正则表达式(也许是HTML5验证正则表达式),则只需说一句话:1.“忽略开头的空白,2.中间需要1-500个字符,3.末尾忽略空白。 ” (使用锚点以确保我们匹配完整的字符串):
// 111 333
// ---------vvv----------vvv
var rex = /^\s*\S.{0,499}\s*$/;
// ------------^^^^^^^^^^
// 2222222222
请注意, \\S
那里至少需要一个非空白字符,然后是0到499个其他字符。
注意:尽管如此,您仍需要trim
字符串,因为另一端的空白会使您超过500个限制。
用法示例:
// NOTE: Using 5 instead of 500 to make tests shorter var rex = /^\\s*\\S.{0,4}\\s*$/; console.log(rex.test("")); // false console.log(rex.test("a")); // true console.log(rex.test(" a ")); // true console.log(rex.test(" 12345 ")); // true console.log(rex.test(" 123456 ")); // false console.log(rex.test("123456")); // false console.log(rex.test("1234 ")); // true console.log(rex.test(" ")); // false
.as-console-wrapper { max-height: 100% !important; }
注意:在JavaScript中, .
与行终止符不匹配。 如果要允许使用这些字符,请使用[\\w\\W]
(任何文字字符或非文字字符)代替.
: /^\\s*[\\w\\W]{1,500}\\s*$/
正则表达式有点超出您的需求。 怎么了
if (myString == null || myString.length > 500){
// handle failed validation here
}
编辑
上面将允许空字符串通过。 1至500次使用
if (myString == null || myString.length < 1 || myString.length > 500){
// handle failed validation here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.