简体   繁体   English

正则表达式只允许两个字,一个空格,最多50个字符

[英]Regex to allow only two words, one space and limit to 50 characters

I'm trying to build a regular expression with the following conditions: 我正在尝试使用以下条件构建正则表达式:

  • Only two words 只有两个字
  • allow one space after the last word 最后一个字后留一个空格
  • Maximum length 50 最大长度50

like ("firstname lastname ") 喜欢(“姓氏姓氏”)

Thanks. 谢谢。

Try this: 尝试这个:

 const validate = data => /^\\w+\\s*\\w+ ?$/.test(data) && data.length <= 50 const testData = ['this works', 'this too ', ' this fails', 'firstname lastname ', ' firstname middlename lastname '] for (let temp of testData) { console.log(`${temp} ${validate(temp)}`) } 

Here is a regex which covers all your requirements, including the length check: 这是一个正则表达式,涵盖了您的所有要求,包括长度检查:

^(?!.{51,})(\w+\s+\w+ ?)$

Explanation: 说明:

^(?!.{51,})    assert that the string is not followed by 51 or more characters
(
    \w+        match a word
    \s+        followed by one or more spaces
    \w+        followed by a second word
     ?         ending with an optional space
)$

 function tests(str){ var regex = /^(?!.{51,})(\\w+\\s+\\w+ ?)$/; if (regex.test(str)) { console.log("passes"); } else { console.log("fails"); } } tests("firstname lastname "); // passes tests("first name last name"); // fails tests("123456789 1234567890123456789012345678901234567890"); // passes (length 50) tests("123456789 12345678901234567890123456789012345678901"); // fails (length 51) 

Regex 101 正则表达式101

 function tests(str){ var pat=/^[a-zA-Z]+\\s[a-zA-Z]+\\s?$/; if(pat.test(str) && str.length<=50){ console.log("true"); } else{ console.log("false"); } } tests("firstname lastname "); //true tests("first name last name"); //flase 

You can check word count by splitting string into array like this 您可以通过将字符串分成这样的数组来检查字数

var array = "some string".split(" "); //result - ["some","string"]

Now you can check word count 现在您可以检查字数

var count = array.length; //will return 2

You can count letters like this 你可以像这样数字母

var letterCount = "some string".length; //will return 11

Way easier and better than using regex. 比使用正则表达式更轻松,更好。

此模式将帮助/^[aZ]+\\s[aZ]+\\s?$/

<input type="text" pattern="^[a-Z]+\s[a-Z]+\s?$" title="Must be two words...">

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

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