简体   繁体   English

正则表达式,用于除数字0以外的任何字母数字字符

[英]regex for any alphanumeric characters except the number 0

For non-zero I have /^[1-9][0-9]*$/ , and for alphanumeric ^[0-9a-zA-Z ]+$ , but I don't know how to combine these. 对于非零,我有/^[1-9][0-9]*$/ ,对于字母数字^[0-9a-zA-Z ]+$ ,但是我不知道如何将它们结合起来。

Please help with regex for any alphanumeric pattern except a single 0 对于除单个0以外的任何字母数字模式,请提供正则表达式帮助

You can use this pattern to prevent matches starting with 0 您可以使用此模式来防止以0开头的匹配

^(?!0)[0-9a-zA-Z ]+$

If 01 is ok but not just 0 use this pattern 如果01可以,但不仅是0使用此模式

^(?!0$)[0-9a-zA-Z ]+$

here what you need : 这里您需要什么:

/^[1-9a-zA-Z ]+$/

Explaination :Allow numbers from 1 to 9, char from A to Z (non sensitive case) and space allowed. 说明:允许数字从1到9,字符从A到Z(不区分大小写)和空格。

Without lookahead you can use: 无需先行,您可以使用:

^[1-9a-zA-Z][0-9a-zA-Z ]*$

Of course with lookahead it is shorter: 当然,使用前瞻,它会更短:

^(?!0$)[0-9a-zA-Z ]+$

There are many good answers to this question. 这个问题有很多好的答案。

But considering the OP's question, I believe the best way to do this would be: 但是考虑到OP的问题,我认为做到这一点的最佳方法是:

(^[1-9a-zA-Z ]$|^[1-9a-zA-Z ][0-9a-zA-Z ]+$)

  • ^[1-9a-zA-Z ]$ if there is only one character ^[1-9a-zA-Z ]$如果只有一个字符

  • ^[1-9a-zA-Z ][0-9a-zA-Z ]+$ if more than one character. ^[1-9a-zA-Z ][0-9a-zA-Z ]+$如果有多个字符)。

I am sorry, none of these worked and I had to read manual and come up with the one that worked. 对不起,这些方法都无效,我不得不阅读手册并提出有效的方法。 I was aided by the answers posted by others. 其他人发布的答案为我提供了帮助。

([^0]|[0-9a-zA-Z_ ]{2,}&)

if one character, not a single zero. 如果是一个字符,则不是一个零。 If more than one character, number, letter, underscore and space are a go. 如果要使用多个字符,数字,字母,下划线和空格。

Tested as follows: 测试如下:

$string0 = 0;
$string1 = 1;
$string2 = 9;
$string3 = '1 - 3 Million'; // is telling this is zero
$string4 = 'false';
$string5 = '0 - 3 Million';
$string6 = '011';
$regex = '([^0]|[0-9a-zA-Z_ ]{2,}&)';
$modifiers = '';
$exp = chr(1) . $regex . chr(1) . $modifiers;
$expresion = $exp;
echo 'CHR(1):'.chr(1).' END';
echo '<br/>';
echo 'EXPRESSION 1:'.$exp.' END';
echo '<br/>';
echo 'Is this non-zero? '.preg_match($expresion, $string0);
echo '<br/>';
echo 'Is this non-zero? '.preg_match($expresion, $string1);
echo '<br/>';
echo 'Is this non-zero? '.preg_match($expresion, $string2);
echo '<br/>';
echo 'Is this non-zero? '.preg_match($expresion, $string3);
echo '<br/>';
echo 'Is this non-zero? '.preg_match($expresion, $string4);
echo '<br/>';
echo 'Is this non-zero? '.preg_match($expresion, $string5);
echo '<br/>';
echo 'Is this non-zero? '.preg_match($expresion, $string6);

OUTPUT OUTPUT

EXPRESSION 1:([^0]|[0-9a-zA-Z_ ]{2,}&) END
Is this non-zero? 0
Is this non-zero? 1
Is this non-zero? 1
Is this non-zero? 1
Is this non-zero? 1
Is this non-zero? 1
Is this non-zero? 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM