简体   繁体   English

字母数字和空格正则表达式,但字符串的开头和结尾没有空格

[英]Alphanumeric and space regex but no space at start and end of string

I want to write a regex that may contains alphabets or number or spaces between word and must be of length between 3 to 50 but not spaces on start and end of string. 我想编写一个正则表达式,其中可能包含字母或数字或单词之间的空格,并且长度必须在3到50之间,但不能在字符串的开头和结尾使用空格。 This is my regex: 这是我的正则表达式:

/^[^-\s]([a-z0-9]|[a-z0-9\s-]){3,50}[^-\s]+$/i

Valid strings: 有效字符串:

uma
umair
umair K

Invalid strings: 无效的字符串:

 uma
u
um
umair 

The last example has a trailing space. 最后一个示例有一个尾随空格。

^(?=.{3,50}$)[^\W_]+(?: [^\W_]+)*$
  • ^ Assert position at the start of the string ^在字符串开头声明位置
  • (?=.{3,50}$) Positive lookahead ensuring between 3 and 50 characters exist before the end of the line (?=.{3,50}$)正行超前确保在行尾之前存在3至50个字符
  • [^\\W_]+ Match any word character except _ one or more times [^\\W_]+匹配除_之外的任何单词字符一次或多次
  • (?: [^\\W_]+)* Match a space followed by one or more word characters, any number of times (?: [^\\W_]+)*匹配一个空格,后跟一个或多个单词字符,任意次
  • $ Assert position at the end of the line $在行尾声明位置

 var r = /^(?=.{3,50}$)[^\\W_]+(?: [^\\W_]+)*$/ var a = [ 'uma','umair','umair K', //valid ' uma','u','um','umair ' //invalid ] a.forEach(function(s){ console.log(r.test(s) ? `Valid: ${s}` : `Invalid: ${s}`) }) 

Alternatives: 备择方案:

^[^\W_][a-zA-Z\d ]{1,48}[^\W_]$

A literal translation of your requirements looks like this: 您的需求的字面翻译如下:

!/[^a-zA-Z\d\s]/.test(str) &&
str.length >= 3 && str.length <= 50 &&
!/^\s/.test(str) &&
!/\s$/.test(str))

Why cram everything in one regex? 为什么要在一个正则表达式中填充所有内容?

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

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