简体   繁体   English

正则表达式和preg_match()

[英]Regular Expressions and preg_match()

I am insanely green with regular expressions. 我是正常表达的疯狂绿色。 Here is what I am trying to accomplish: I want to require an 8 character password that allows upper and lowercase letters, numbers and !@#$%^&*-_ characters. 这是我要完成的工作:我需要一个8个字符的密码,该密码允许使用大写和小写字母,数字和!@#$%^&* -_字符。 Here is what I have that doesn't appear to be working: 以下是我看似不起作用的内容:

preg_match('([A-za-z0-9-_!@#$%^&*]{8,})', $password)

Am I missing something really obvious? 我错过了一些非常明显的东西吗

Update: Yes, I was missing something really obvious - the open bracket [. 更新:是的,我确实缺少一些明显的东西-右括号[。 However it still returns true when I use characters like a single quote or bracket. 但是,当我使用单引号或方括号之类的字符时,它仍然返回true。 (Which are what I am trying to avoid.) (这是我要避免的。)

Basically you miss an opening [ character group bracket here: 基本上,您会错过开头[这里的字符组括号:

              ↓
 preg_match('([A-za-z0-9-_!@#$%^&*()]{8,})', $password)

And you should also use delimiters . 你还应该使用分隔符 The parens will behave as such, but it's better to use a different pair to avoid ambiguity with a capture group: paren的行为将是这样,但是最好使用不同的对,以免与捕获组产生歧义:

 preg_match('/^([A-za-z0-9-_!@#$%^&*()]{8,})$/', $password)

This also adds start ^ and end $ assertions to match the whole string. 这也添加了start ^和end $ assertions以匹配整个字符串。

This may be easier to break into individual rules. 这可能更容易打破个别规则。 Ie a rule to check if the password is at least 8 characters long, another to check for an uppercase, another for lowercase, etc. 例如,检查密码是否至少8个字符,另一个检查是否为大写,另一个是否为小写,等等。

Also, it looks like you have some special characters in terms of regular expressions without any escaping. 另外,看起来您在正则表达式方面有一些特殊字符,没有任何转义。 For example, the * character has special meaning in regular expressions other than some special cases. 例如,除了某些特殊情况之外,*字符在正则表达式中具有特殊含义。 It either needs to be escaped \\* or in brackets [*] 它需要转义\\*或放在括号[*]

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

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