简体   繁体   English

输入字段中不允许有空格的正则表达式

[英]Regular expression for not allowing spaces in the input field

I have a username field in my form.我的表单中有一个用户名字段。 I want to not allow spaces anywhere in the string.我不想在字符串中的任何地方允许空格。 I have used this regex:我用过这个正则表达式:

var regexp = /^\S/;

This works for me if there are spaces between the characters.如果字符之间有空格,这对我有用。 That is if username is ABC DEF .也就是说,如果用户名是ABC DEF It doesn't work if a space is in the beginning, eg <space><space>ABC .如果开头有空格,则不起作用,例如<space><space>ABC What should the regex be?正则表达式应该是什么?

While you have specified the start anchor and the first letter, you have not done anything for the rest of the string.当您指定了起始锚点和第一个字母时,您还没有为字符串的其余部分做任何事情。 You seem to want repetition of that character class until the end of the string :您似乎想要重复字符类,直到字符串结束

var regexp = /^\S*$/; // a string consisting only of non-whitespaces

使用+加号(匹配一个或多个前面的项目),

var regexp = /^\S+$/

这将有助于找到开头、中间和结尾的空格:

var regexp = /\\s/g

If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()如果您正在使用一些接受字符串并使用构造 Regex 的插件来创建 Regex 对象 i:e new RegExp()

Than Below string will work比下面的字符串将起作用

'^\\S*$'

It's same regex @Bergi mentioned just the string version for new RegExp constructor同样的正则表达式@Bergi 只提到了新的 RegExp 构造函数的字符串版本

This one will only match the input field or string if there are no spaces.如果没有空格,这将仅匹配输入字段或字符串。 If there are any spaces, it will not match at all.如果有任何空格,它将根本不匹配。

/^([A-z0-9!@#$%^&*().,<>{}[\\]<>?_=+\\-|;:\\'\\"\\/])*[^\\s]\\1*$/

Matches from the beginning of the line to the end.从行首到行尾匹配。 Accepts alphanumeric characters, numbers, and most special characters.接受字母数字字符、数字和大多数特殊字符。

If you want just alphanumeric characters then change what is in the [] like so:如果您只想要字母数字字符,则更改 [] 中的内容,如下所示:

/^([Az])*[^\\s]\\1*$/

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

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