正则表达式,检测字符串中没有空格

Regex, detect no spaces in the string

这是我当前的正则表达式检查:

const validPassword = (password) => password.match(/^(?=.*\d)(?=.\S)(?=.*[a-zA-Z]).{6,}$/);

我的支票至少包含 1 个字母和 1 个数字,且长度至少为 6 个字符。但是我也想确保字符串中的任何地方都没有空格。

到目前为止,我可以输入包含空格的 6 个字符串:(

在这里找到了这个答案,但出于某种原因在我的代码中它通过了。

What is the regular expression for matching that contains no white space in between text?

看来你需要

/^(?=.*\d)(?=.*[a-zA-Z])\S{6,}$/

详情

  • ^ - 字符串开头
  • (?=.*\d) - 1 位数(至少)
  • (?=.*[a-zA-Z]) - 至少 1 个字母
  • \S{6,} - 6 个或更多非空白字符
  • $ - 字符串锚点的结尾

考虑到 principle of contrast,您可以将模式修改为

/^(?=\D*\d)(?=[^a-zA-Z]*[a-zA-Z])\S{6,}$/