简体   繁体   中英

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. Now program fails and cannot find pattern.

You may add an optional : after password , and match 0 or more whitespaces with \s* :

password:?\s*(\w+)

See the regex demo .

Details

  • password - a fixed string
  • :? - 1 or 0 colons
  • \s* - 0+ whitespaces
  • (\w+) - Capturing group 1: one or more word chars.

Java demo :

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:

SECRET115
PASS111

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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