I am trying to solve an exercise in which I have to print the password in a given text. The rules are:
a password consists of digits and Latin upper- and lowercase letters; a password always follows the word "password" (it can be written in upper- or lowercase letters), but can be separated from it by any number of whitespaces and colon : characters.
My problem is that I need to make sure that the password is preceded by "password" and a random number of whitespaces and a colon, but I also must print the password only.
For example, if the input is:
My email javacoder@gmail.com with password SECRET115. Here is my old PASSWORD: PASS111.
The output should be:
SECRET115
PASS111
I stumbled upon lookaheads and lookbehinds and tried them in my regex:
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
Pattern pattern = Pattern.compile("(?<=password[\\s:]*)\\w*(?=\\W)", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(text);
if (!matcher.find()) {
System.out.println("No passwords found.");
}
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
This solution does print passwords only, but it also prints extra newlines for no reason. The output for the above input looked like this:
SECRET115
PASS111
Also, when I try to change the regex to "(?<=password[\\s:]*)\\w{5,}(?=\\W)" so that the password accepted be at least of length 5, the program outputs just:
PASS111
The other password is clearly longer than 5 characters, why was it left out?