[英]Regular expression to check characters in a string
I have a text to validate using regex, 我有一条文本可以使用正则表达式进行验证,
Text field is allowed to have all the characters az and 0-9 except for alphabets (i,o,q). 允许文本字段包含所有字符az和0-9,但字母(i,o,q)除外。
I tried something like this but cannot get it to work '/[^(oOiIqQ)]/'
我尝试过类似的操作,但无法使其正常运行'/[^(oOiIqQ)]/'
A simple way for exclusions like this is to use negative lookahead. 进行此类排除的一种简单方法是使用否定前瞻。 State what you want: 陈述你想要什么:
/^(?:[a-z0-9])+\z/i
Then exclude the items you don't want: 然后排除您不想要的项目:
/^(?:(?![ioq])[a-z0-9])+\z/i
You cannot use parenthesis in [ ... ]. 您不能在[...]中使用括号。
You have to use something like '/[0-9a-hj-npr-zA-HJ-NPR-Z]/' 您必须使用类似“ / [0-9a-hj-npr-zA-HJ-NPR-Z] /”的名称
If you want to be sure your text only has those characters, use: 如果要确保文本仅包含那些字符,请使用:
'/^[0-9a-hj-npr-zA-HJ-NPR-Z]+$/'
So you can match a string containing any number of those characters, and only those. 因此,您可以匹配包含任意数量的那些字符的字符串,并且仅包含那些字符。
This might works: [a-hj-npr-z]
Maybe you can add the flag i
at the end of your regexp for case insensibility. 这可能会起作用: [a-hj-npr-z]
也许您可以在正则表达式的末尾添加标记i
,以区分大小写。
(yours will allow EVERY characters except those you specified) (您将允许您指定的字符以外的所有字符)
if (preg_match('#^[0-9a-hj-npr-z]+$#i', $string)) {
//string OK
}
也许是这样的/^[0-9a-hj-npr-z A-HJ-NPR-X]+$/
我假设对您的做了一些改动,然后尝试:
^[^oOiIqQ]+$
为此,有一个非常简单的解决方案,其中考虑了负正则表达式(这使正则表达式更短且更具可读性)
[^ioqIOQ]+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.