javascript - 允许单词字符、括号、空格和连字符的正则表达式

标签 javascript regex

我正在尝试在 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

关于javascript - 允许单词字符、括号、空格和连字符的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15883097/

相关文章:

javascript - Node.js:如果声明为粗箭头,则函数 "not defined"

javascript - 找到某些/特定的换行符,同时忽略其他换行符

Python 正则表达式 : how to check if a character in a string is within the span of a regex matched substring?

mysql - 正则表达式到 SQL : repetition-operator operand invalid

Ruby 正则表达式不匹配

javascript - react-router-dom 如何向后导航(不在历史记录中)

javascript - 在 map 上显示移动标记

c# - 以逗号分隔的整数的正则表达式

javascript - 匹配并用四个空格替换行首的所有制表符

javascript - 在附加 HTML 时执行 IF 语句的多个实例的更好方法?