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

后端 未结 11 794
夕颜
夕颜 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:45

    jjnguy had it correct (if slightly redundant) in an earlier revision.

    .*?[^0-9].*
    

    @Chad, your regex,

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

    should probably allow for non letters (eg, punctuation) even though Svish's examples didn't include one. Svish's primary requirement was: not all be digits.

    \b.*[^0-9]+.*\b
    

    Then, you don't need the + in there since all you need is to guarantee 1 non-digit is in there (more might be in there as covered by the .* on the ends).

    \b.*[^0-9].*\b
    

    Next, you can do away with the \b on either end since these are unnecessary constraints (invoking reference to alphanum and _).

    .*[^0-9].*
    

    Finally, note that this last regex shows that the problem can be solved with just the basics, those basics which have existed for decades (eg, no need for the look-ahead feature). In English, the question was logically equivalent to simply asking that 1 counter-example character be found within a string.

    We can test this regex in a browser by copying the following into the location bar, replacing the string "6576576i7567" with whatever you want to test.

    javascript:alert(new String("6576576i7567").match(".*[^0-9].*"));
    

提交回复
热议问题