javascript 正则表达式:只有字母数字但不是纯数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11773297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:17:42  来源:igfitidea点击:

Regex: only alphanumeric but not if this is pure numeric

javascriptregex

提问by oldergod

For instance:

例如:

'1'     => NG
'243'   => NG
'1av'   => OK
'pRo'   => OK
'123k%' => NG

I tried with

我试过

 /^(?=^[^0-9]*$)(?=[a-zA-Z0-9]+)$/

but it is not working very well.

但它工作得不是很好。

回答by Jens

Use

利用

/^(?![0-9]*$)[a-zA-Z0-9]+$/

This expression has a negative lookahead to verify that the string is not only numbers. See it in action with RegExr.

这个表达式有一个否定的前瞻来验证字符串不仅仅是数字。使用RegExr查看它的实际效果

回答by Andrzej Doyle

So we know that there must be at least one "alphabetic" character in there somewhere:

所以我们知道某处必须至少有一个“字母”字符:

[a-zA-Z]

And it can have any number of alphanumeric characters (including zero) either before it or after it, so we pad it with [a-zA-Z0-9]*on both sides:

它可以在它之前或之后有任意数量的字母数字字符(包括零),所以我们在它的[a-zA-Z0-9]*两边填充它:

/^[a-zA-Z0-9]*[a-zA-Z][a-zA-Z0-9]*$/

That should do the trick.

这应该够了吧。

回答by MaxArt

Try with this:

试试这个:

/^(?!^\d*$)[a-zA-Z\d]*$/

Edit: since this is essentially the same of the accepted answer, I'll give you something different:

编辑:由于这与接受的答案基本相同,我会给你一些不同的东西:

/^\d*[a-zA-Z][a-zA-Z\d]*$/

No lookaheads, no repeated complex group, it just verifies that there's at least one alphabetic character. This should be quite fast.

没有前瞻,没有重复的复杂组,它只是验证至少有一个字母字符。这应该是相当快的。

回答by godspeedlee

try with this: ^(?!\d+\b)[a-zA-Z\d]+$
(?!\d+\b)will avoid pure numeric, add \w+ then mix alphabet and number.

试试这个:^(?!\d+\b)[a-zA-Z\d]+$
(?!\d+\b)将避免纯数字,添加 \w+ 然后混合字母和数字。

回答by user2184688

Try this: ^[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$

试试这个: ^[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$

回答by Abhishek Gehlot

this is strictly alphanumeric

这是严格的字母数字

String name="^[^a-zA-Z]\d*[a-zA-Z][a-zA-Z\d]*$";

回答by davidrac

This should do the trick, without lookbehind:

这应该可以解决问题,无需回头看:

^(\d*[a-zA-Z]\d*)+$