Regex允许单词字符、括号、空格和连字符

Regex to allow word characters, parentheses, spaces and hyphen

本文关键字:空格 连字符 括号 Regex 许单词 字符      更新时间:2023-09-26

我试图验证javascript中的正则表达式字符串。字符串可以有:

  • 字字符
  • 括号
  • 连字符(-)
  • 3 ~ 50长度

这是我的尝试:

function validate(value, regex) {
    return value.toString().match(regex);
}
validate(someString, '^['w's/-/(/)]{3,50}$');

像这样编写验证器

function validate(value, re) {
  return re.test(value.toString());
}

使用这个正则表达式

/^['w() -]{3,50}$/

一些测试

// spaces
validate("hello world yay spaces", /^['w() -]{3,50}$/);
true
// too short
validate("ab", /^['w() -]{3,50}$/);
false
// too long
validate("this is just too long we need it to be shorter than this, ok?", /^['w() -]{3,50}$/);
false
// invalid characters
validate("you're not allowed to use crazy $ymbols", /^['w() -]{3,50}$/);
false
// parentheses are ok
validate("(but you can use parentheses)", /^['w() -]{3,50}$/);
true
// and hyphens too
validate("- and hyphens too", /^['w() -]{3,50}$/);
true