Regex: How to match a string that is not only numbers

后端 未结 11 735
夕颜
夕颜 2020-11-30 03:18

Is it possible to write a regular expression that matches all strings that does not only contain numbers? If we have these strings:

  • abc
相关标签:
11条回答
  • 2020-11-30 03:31
    (?!^\d+$)^.+$
    

    This says lookahead for lines that do not contain all digits and match the entire line.

    0 讨论(0)
  • 2020-11-30 03:33

    Since you said "match", not just validate, the following regex will match correctly

    \b.*[a-zA-Z]+.*\b
    

    Passing Tests:

    abc
    a4c
    4bc
    ab4
    1b1
    11b
    b11
    

    Failing Tests:

    123
    
    0 讨论(0)
  • 2020-11-30 03:38

    Try this:

    /^.*\D+.*$/
    

    It returns true if there is any simbol, that is not a number. Works fine with all languages.

    0 讨论(0)
  • 2020-11-30 03:41

    Unless I am missing something, I think the most concise regex is...

    /\D/
    

    ...or in other words, is there a not-digit in the string?

    0 讨论(0)
  • 2020-11-30 03:41

    if you are trying to match worlds that have at least one letter but they are formed by numbers and letters (or just letters), this is what I have used:

    (\d*[a-zA-Z]+\d*)+
    
    0 讨论(0)
  • 2020-11-30 03:41

    I am using /^[0-9]*$/gm in my JavaScript code to see if string is only numbers. If yes then it should fail otherwise it will return the string.

    Below is working code snippet with test cases:

    function isValidURL(string) {
      var res = string.match(/^[0-9]*$/gm);
      if (res == null)
        return string;
      else
        return "fail";
    };
    
    var testCase1 = "abc";
    console.log(isValidURL(testCase1)); // abc
    
    var testCase2 = "a4c";
    console.log(isValidURL(testCase2)); // a4c
    
    var testCase3 = "4bc";
    console.log(isValidURL(testCase3)); // 4bc
    
    var testCase4 = "ab4";
    console.log(isValidURL(testCase4)); // ab4
    
    var testCase5 = "123"; // fail here
    console.log(isValidURL(testCase5));

    0 讨论(0)
提交回复
热议问题