I have a text file having the following design:
FirstName= xxxxx
LastName= xxxxx
Username= qwerty
Password= qwerty100
Email ID= [email protected]
PhoneNumber= 12345678
____________
FirstName= yyyyy
LastName= yyyyy
Username= qwerty999
Password= pass100
Email ID= [email protected]
PhoneNumber= 1235326
I have the task to code a login/signup program.The above text is generated by the signup form.The sign up program asks the user to input user name and password and if it matches any of the username with its corresponding password, the user successfully logs in with a successfully logged in message on the terminal
For example: If the user inputs username: qwerty999 and password: pass100, the program shows a successfully logged in message and if no database is found matching the user input, a error message is displayed and the program terminates
My main problem is that I cannot search for the input username and password input by the user in the text file. I want it to be searched and store in another variable which the program can compare with the user input
CodePudding user response:
After you got the file data as a string you can use Regex named group to check if this user is existing or not, for example, this code will check if it exists it will return the other info to you, and if not it will give you error message, you can extend it
public static void main(String[] args) {
String input = "FirstName= xxxxx\n"
"LastName= xxxxx\n"
"Username= qwerty\n"
"Password= qwerty100\n"
"Email ID= [email protected]\n"
"PhoneNumber= 12345678\n"
"\n"
"____________\n"
"\n"
"FirstName= yyyyy\n"
"LastName= yyyyy\n"
"Username= qwerty999\n"
"Password= pass100\n"
"Email ID= [email protected]\n"
"PhoneNumber= 1235326";
String username = "qwerty";
String password = "qwerty100";
Pattern pattern = Pattern.compile(
"FirstName= ([a-zA-Z] )\n"
"LastName= ([a-zA-Z] )\n"
"Username= " Pattern.quote(username) "\n"
"Password= " Pattern.quote(password) "\n"
"Email ID= (. )\n"
"PhoneNumber= (\\d )");
Matcher matcher = pattern.matcher(input);
boolean isValidUser = matcher.find();
if (isValidUser) {
String firstName = matcher.group(1);
String lastName = matcher.group(2);
String emailId = matcher.group(3);
String phoneNumber = matcher.group(4);
} else {
System.out.println("No User with this username and password");
}
}
For more info about this topic search for Regex named group