简体   繁体   English

如何使用正则表达式查找密码

[英]How to find passwords with regex

A password consists of digits and Latin letters in any case;在任何情况下,密码都由数字和拉丁字母组成; a password always follow by the "password" word (in any case), but they can be separated by any number of spaces and the colon: characters.密码总是后跟“密码”字(在任何情况下),但它们可以用任意数量的空格和冒号分隔:字符。

I try this regular expression我试试这个正则表达式

Pattern pattern = Pattern.compile("password\\s\\w*",Pattern.CASE_INSENSITIVE);

If text is如果文本是

    String text = "My email javacoder@gmail.com with password    SECRET115. Here is my old PASSWORD: PASS111.\n";//scanner.nextLine();

We need to find SECRET115 and PASS111.我们需要找到 SECRET115 和 PASS111。 Now program fails and cannot find pattern.现在程序失败并且找不到模式。

You may add an optional : after password , and match 0 or more whitespaces with \s* :您可以在password之后添加一个可选的: ,并将 0 个或多个空格与\s*匹配:

password:?\s*(\w+)

See the regex demo .请参阅正则表达式演示

Details细节

  • password - a fixed string password - 固定字符串
  • :? - 1 or 0 colons - 1 或 0 个冒号
  • \s* - 0+ whitespaces \s* - 0+ 个空格
  • (\w+) - Capturing group 1: one or more word chars. (\w+) - 捕获组 1:一个或多个单词字符。

Java demo : Java 演示

String s = "My email javacoder@gmail.com with password    SECRET115. Here is my old PASSWORD: PASS111.\n";
Pattern pattern = Pattern.compile("password:?\\s*(\\w+)", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
    System.out.println(matcher.group(1)); 
} 

Output: Output:

SECRET115
PASS111

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

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