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

后端 未结 11 776
夕颜
夕颜 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: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));

提交回复
热议问题