简体   繁体   English

无效的转义序列 \d

[英]Invalid escape sequence \d

I'm trying to check if a password contain at least one lower case letter, one upper case letter, one digit and one special character.我正在尝试检查密码是否至少包含一个小写字母、一个大写字母、一个数字和一个特殊字符。

i'm trying this:我正在尝试这个:

if(!password.matches("(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])")){
        username = "Error";
    }

but give me an error saying: invalid escape sequence.但给我一个错误说:无效的转义序列。

Someone can help me to solve the problem and can confirm that is a correct pattern?有人可以帮我解决问题并确认这是正确的模式吗?

Thanks, whit \\d don't do error but it don't match with a string like Paul%88 why?谢谢,whit \\d 不会出错,但它与 Paul%88 这样的字符串不匹配,为什么?

Java will treat \ inside a string as starting an escape sequence . Java 会将字符串中的\视为开始转义序列 Make sure you use \\ instead (so that you get an actual \ character in the string) and you should be ok.确保你使用\\代替(这样你就可以在字符串中得到一个实际的\字符),你应该没问题。

Quick Update : As Etienne points out, if you actually want a \ in the RegEx itself, you'll need to use \\\\ , since that will produce \\ in the string, which will produce \ in the RegEx.快速更新:正如 Etienne 指出的那样,如果你真的想要 RegEx 本身中的\ ,你需要使用\\\\ ,因为这将在字符串中产生\\ ,这将在 RegEx 中产生\

New Question Update: You mention that your RegEx doesn't work, and I'm pretty sure that's because it's wrong.新问题更新:您提到您的 RegEx 不起作用,我很确定那是因为它是错误的。 If you just want to ensure one of each type of character class is present, you may just want to create one RegEx for each class, and then check the password against each one.如果您只想确保存在每种类型的字符 class 之一,您可能只想为每个 class 创建一个 RegEx,然后对照每个字符检查密码。 Passwords are pretty much guaranteed to be short (and you can actually control that yourself) so the perf hit should be minimal.密码几乎可以保证很短(您实际上可以自己控制),因此性能命中应该是最小的。

I used this to quickly test it: http://www.regexplanet.com/simple/index.html我用它来快速测试它: http://www.regexplanet.com/simple/index.html

Looks like it works if you put.* at the end.如果你把。*放在最后,看起来它会起作用。 I guess you need to actually include a non-look-ahead regex as well.我想您实际上还需要包含一个非前瞻正则表达式。

Here is the entire regex:这是整个正则表达式:

(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*

Of course in your java code you must escape the backslash as mentioned already.当然,在您的 java 代码中,您必须如前所述转义反斜杠。

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

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