首页 文章

正则表达式只允许两个单词,一个空格和限制为50个字符

提问于
浏览
-1

我正在尝试使用以下条件构建正则表达式:

  • 只有两个字

  • 在最后一个单词后面允许一个空格

  • 最大长度50

喜欢(“firstname lastname”)

谢谢 .

5 回答

  • 1

    试试这个:

    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)}`)
    }
    
  • 0

    这是一个正则表达式,涵盖了您的所有要求,包括长度检查:

    ^(?!.{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)
    

    正则表达式101

  • 1
    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
    
  • 0

    您可以通过将字符串拆分为数组来检查字数

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

    现在你可以检查字数了

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

    你可以算上这样的字母

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

    比使用正则表达式更简单,更好 .

  • 0

    这种模式有助于 /^[a-Z]+\s[a-Z]+\s?$/

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

相关问题