简体   繁体   English

简单的正则表达式以匹配某些字符并排除其他字符

[英]Simple regex to match some characters and exclude others

I need a regex for preg_match to accept all alphanumeric characters except l , L , v , V , 0 , 2 . 我需要一个正则表达式的preg_match接受除了所有字母数字字符lLvV02

I've tried 我试过了

^[a-zA-Z0-9][^lLvV02]*$

It works good excluding lLvV02 but it also accept other characters like SPACE,ù,@,#, etc... 除了lLvV02之外,它都可以正常工作,但它也可以接受其他字符,例如SPACE,ù,@,#等。

How should I change it? 我该如何更改?

You may use 您可以使用

^(?:(?![lLvV02])[a-zA-Z0-9])*$

Details 细节

  • ^ - start of string ^ -字符串开头
  • (?: - start of a non-capturing group (?: -开始非捕获组
    • (?![lLvV02])[a-zA-Z0-9] - an alnum char that is not one of the chars inside the character class residing inside a negative lookahead (?![lLvV02])[a-zA-Z0-9] -一个不属于负前瞻性的字符类中的字符之一
  • )* - end of the non-capturing group, 0 or more repetitions )* -非捕获组的结尾,重复0个或更多
  • $ - end of string $ -字符串结尾

See the Regulex graph : 参见Regulex图

在此处输入图片说明

I know you asked for a Regex, but you can test for alphanumeric first and only if that passes check that the others are NOT present: 我知道您要求使用正则表达式,但是您可以先测试字母数字,并且只有在通过后才能检查其他字符是否存在:

if(ctype_alnum($string) && !preg_match('/[lLvV02]/', $string)) {
    //pass
} else {
    //fail
}

Or possibly substitute preg_match('/^[^lLvV02]+$/', $string) . 或者可能替代preg_match('/^[^lLvV02]+$/', $string)

Easiest would probably be: ^[a-km-uw-zA-KM-UW-Z13-9]*$ . 最简单的可能是: ^[a-km-uw-zA-KM-UW-Z13-9]*$ I'm not saying that it's pretty but it does what it's supposed to. 我并不是说它很漂亮,但是可以达到预期的效果。

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

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