import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Generate your Security Code ");
String password=sc.next();
if(password.length()>=8)
{
Pattern letter = Pattern.compile("[a-z]{1}[A-z]{1}");
Pattern digit = Pattern.compile("[0-9]");
Pattern special = Pattern.compile ("[##*]{1}");
Matcher hasLetter = letter.matcher(password);
Matcher hasDigit = digit.matcher(password);
Matcher hasSpecial = special.matcher(password);
if(hasLetter.find() && hasSpecial.find() &&hasDigit.find()){
System.out.println("Security Code Generated Successfully");
}
}
else{
System.out.println("Invalid Security Code, Try Again!");
}
}
}
I wrote a code for password generation but one test case is failing,the digits in password are not compulsory how do i do it?
List item
If you want to change the regex for optional digit then add a * .
Another way around is to use || instead of &&
if(hasLetter.find() && hasSpecial.find() ||hasDigit.find()){
System.out.println("Security Code Generated Successfully");
}
Related
This is from Liang's Java Book. Basically, I have to check with a method if a certain word could be used as password.
/*
(Check password) Some websites impose certain rules for passwords. Write a
method that checks whether a string is a valid password. Suppose the password
rules are as follows:
■ A password must have at least eight characters.
■ A password consists of only letters and digits.
■ A password must contain at least two digits.
Write a program that prompts the user to enter a password and displays Valid
Password if the rules are followed or Invalid Password otherwise.
*/
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("This program checks if the password prompted is valid, enter a password:");
Scanner input = new Scanner(System.in);
String password = input.nextLine();
if (isValidPassword(password))
System.out.println("The password is valid.");
else
System.out.println("The password is not valid.");
public static boolean isValidPassword (String password) {
if (password.length() >= 8) {
// if (regex to include only alphanumeric characters?
// if "password" contains at least two digits...
return true;
}
Also, what if (not required) would I to display the exact kind of error? For instance, if I would notify the user that only a kind of error has occurred (e.g. "Your password length is OK, but there are no digits in your password")?
I would do this way:
public class Test {
public static String passwordChecker(String s){
String response = "The password";
int countdigits = 0;
Pattern pattern = Pattern.compile("[0-9]");
Matcher matcher = pattern.matcher(s);
while(matcher.find()){
++countdigits;
}
if(s.length() >= 8){
response = response + ": \n-is too short (min. 8)";
}
else if(!(s.toLowerCase().matches("[a-z]+") && s.matches("[0-9]+"))){
response = response + "\n-is not alphanumeric";
}
else if(countdigits < 2){
response = response + "\n-it doesn't contains at least 2 digits";
}
else{
response = response + " ok";
}
return response;
}
public static void main(String[] args) {
System.out.println("This program checks if the password prompted is valid, enter a password:");
Scanner input = new Scanner(System.in);
String password = input.nextLine();
System.out.println(passwordChecker(password));
}
}
Oops, I forgot to add the rules; well, just use System.out.println :)
I am not very experienced with Selenium. I thought to test my knowledge by doing the following, validate that a name field in a form has no special character. I was not able to do so. 1st I tried to put the characters in an array and read from the array but I kept on getting Alert failure message. Then I thought of the following way and always getting output "valid".
import junit.framework.Assert;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class NameField {
public static FirefoxDriver fx= new FirefoxDriver();
public static String doCheck()
{
fx.get("http://www.gogamers.com/#!blank/gs4id");
String regex = "^[A-Z0-9+$";
String str=fx.findElement(By.id("comp-iikjotq8nameField")).getText();
fx.findElement(By.id("comp-iikjotq8nameField")).sendKeys("#john");
if (str.matches("[" + regex + "]+")){
System.out.println("Invalid character in Name field");
}
else{
System.out.println("valid");
}
return str;
What I have in mind is if you give a name using sendkey(eg: John#, #john) you will get invalid message. Another thing I was thinking should I use assertion? Please suggest a best way a small sample code would be helpful.
The new code that I have tried today which is still giving me Valid, when I am expecting invalid. Can someone kindly take a look please? I tried both matches and find
public class YahooMail {
public static void main(String[] args) {
FirefoxDriver fx= new FirefoxDriver();
fx.get("https://login.yahoo.com/account/create?");
String title=fx.getTitle();
Assert.assertTrue(title.contains("Yahoo"));
//First I send a text, then I get the text
fx.findElement(By.id("usernamereg-firstName")).sendKeys("$John");
fx.findElement(By.id("usernamereg-firstName")).getText();
//This is the String I want to find
String firstName="John";
//If there are these symbols associated with the name-show invalid
String patternString = ".*$%^#:.*";
Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(firstName);
if(matcher.find()){
System.out.println("Invalid Name" );
}
else{
System.out.println("Valid Name");
}
}
}
You can fix your regular expression to match any non-alphanumeric characters and use Pattern and Matcher instead:
Pattern p = Pattern.compile("\\W");
Matcher m = p.matcher(str);
if (m.find()) {
System.out.println("Invalid character in Name field");
}
else {
System.out.println("valid");
}
What I did to validate a name field I used same regular expression as was used by our developers in website. Name field in my case is only accepting alphanumeric characters. First of all I created a java functions to randomly generate alphanumeric with special characters as below and then I am comparing this auto generated input with actual regular expressions. As special characters are not allowed in my case, if statement will return false and else block will be executed showing that special characters are not allowed.
//can also be used for complex passwords
public String randomSpecial(int count)
{
String characters = "~`!##$%^&*()-_=+[{]}\\|;:\'\",<.>/?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
String generatedString = RandomStringUtils.random(count, characters);
return generatedString;
}
public void TC_05_regExpression_Invalid()
{
String regex = "/^[a-zA-Z0-9- ]*$/";
WebElement element = driver.findElement(By.name("firstName"));
element.sendKeys(randomSpecial(10));
String fieldText = element.getAttribute("value");
if(fieldText.matches("["+ regex + "]+"))
{
logger.info("Valid Input: " + fieldText);
}
else
{
logger.info("InValid Input: " + fieldText + "not allowed");
}
element.clear();
}
It is working now, the problem is I was not capturing the sendKeys value. I should have used getAttribute
f.get("https://mail.yahoo.com");
f.findElement(By.id("login-username")).sendKeys("jj%jo.com");
//The getAttribute method returns the value of an attribute of an HTML Tag;
//for example if I have an input like this:
WebElement element = f.findElement(By.id("login-username"));
String text = element.getAttribute("value");
System.out.println(text);
if((text).contains("#")){
System.out.println("pass");
}
else{
System.out.println("not pass");
}
enter code here
public class Personal_loan {
public String verified_number(String inputNumber) // pass the parameter
{
String validation;
String regexNum = "[0-9]+"; //"[A-Za-z]";//"^[A-Z+$]";
if (inputNumber.matches("[" + regexNum + "]+"))
{
System.out.println("valid");
validation="valid";
}
else{
System.out.println("Invalid character in Name field");
validation="invalid";
}
return validation;
}
public String verified_str(String inputStr)
{
String regexString = "[A-Za-z]";//"^[A-Z+$]";
if (inputStr.matches("[" + regexString + "]+"))
{
System.out.println("valid");
}
else{
System.out.println("Invalid character in Name field");
}
return null;
}
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.iservefinancial.com/");
driver.findElement(By.xpath("(//DIV[#itemprop='name'])[1]")).click();
WebElement LoanAmount =driver.findElement(By.xpath("//INPUT[#id='amount_qa']"));
WebElement Income =driver.findElement(By.xpath("//INPUT[#id='income_qa']"));
LoanAmount.sendKeys("12345");
Income.sendKeys("amount");
Personal_loan pl=new Personal_loan(); //creating object
String g = LoanAmount.getAttribute("value"); // store the value in string
String incomevalue = Income.getAttribute("value");
String lavalid=pl.verified_number(g);
String income_valid = pl.verified_number(incomevalue);
System.out.println("Loan Amount "+lavalid);
System.out.println("income Amount "+income_valid);
}
}
I've string like below , want to get the value of cn=ADMIN , but dont know how to get to using regex efficient way.
group:192.168.133.205:387/cn=ADMIN,cn=groups,dc=mi,dc=com,dc=usa
well ... like this?
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexSample {
public static void main(String[] args) {
String str = "group:192.168.133.205:387/cn=ADMIN,cn=groups,dc=mi,dc=com,dc=usa";
Pattern pattern = Pattern.compile("^.*/(.*)$");
Matcher matcher = pattern.matcher(str);
if (matcher.matches()) {
String right = matcher.group(1);
String[] parts = right.split(",");
for (String part : parts) {
System.err.println("part: " + part);
}
}
}
}
Output is:
part: cn=ADMIN
part: cn=groups
part: dc=mi
part: dc=com
part: dc=usa
String bubba = "group:192.168.133.205:387/cn=ADMIN,cn=groups,dc=mi,dc=com,dc=usa";
String target = "cn=ADMIN";
for(String current: bubba.split("[/,]")){
if(current.equals(target)){
System.out.println("Got it");
}
}
Pattern for regex
cn=([a-zA-Z0-9]+?),
Your name will be in group 1 of matcher. You can extend character classes if you allow spaces etc.
Hi I'm trying to setup a hostname pattern for a minecraft-server plugin. It will look through the arguments of the chat message and try to find any possible hostnames. The code works unless the message only contains one word.
Here's the class that checks the message event:
package com.carlgo11.preventip.player;
import com.carlgo11.preventip.Main;
import java.util.regex.Matcher;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
public class ChatEvent implements Listener {
Main plugin;
public ChatEvent(Main plug)
{
super();
this.plugin = plug;
}
#EventHandler
public void PlayerChat(AsyncPlayerChatEvent e)
{
if (!plugin.getConfig().getBoolean("ignore-chat")) {
Player p = e.getPlayer();
String msg = e.getMessage();
String[] args = msg.split(" ");
Boolean match = false;
if (!p.hasPermission("preventip.ignore")) {
for (int i = 0; i < args.length; i++) {
Matcher hnre = plugin.hostnamePattern.matcher(msg.toString());
Boolean hnrematch = hnre.find();
if (hnrematch) {
match = true;
break;
}
}
if (match) {
e.setCancelled(true);
Action.action(p, plugin);
}
}
}
}
}
And here's the pattern
Pattern hostnamePattern = Pattern.compile("^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$");
So when args contains more than 1 word the pattern works but if not the pattern acts as true even though hnre.find() outputs false.
Thanks in advance :)
First at all, please use Java Naming Conventions (see https://stackoverflow.com/tags/java/info).
About your method design there is something that I find a little strange, first you split the message:
String[] args = msg.split(" ");
but then you try to match your regex with the whole message, for each word in your message:
Matcher hnre = plugin.hostnamePattern.matcher(msg.toString());
I think you can simplify all doing something like:
//remove ^ and $ to find the pattern in any position in your message. I assume the correctness of the pattern
Pattern hostnamePattern = Pattern.compile("(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])");
//Let msg a annoying message
String msg = "ereh un enfermo, ereh un enfermo, ereh un enfermo de ciberseso me pone loh cuenno " +
"me pone lo cuenno www.tiahbuena.com esto vida mia eh un infienno";
Matcher m = hostnamePattern.matcher(msg);
boolean hnrematch = m.find();
if(hnrematch){
//cancel what you want
}
Hope it helps
How exactly do i validate the domain part of an email address? Do i need to first list out the existing domains in my java class or java's InternetAddress.validate() will perform it by default? I have used this:
public static boolean verifyEmailAddress(String regEmail) {
boolean result = true;
try {
InternetAddress emailAddr = new InternetAddress(regEmail);
emailAddr.validate();
} catch (AddressException ex) {
result = false;
}
return result;
}
The request.getParameter has an email address and stored in regEmail..
The problem is even for invalid emails like san#hhhgggmail.com its showing valid.. What exactly do i need to do.. Help me out.. And also is this function working fine to those who have used it and tested ?
I think you are approaching the problem from the wrong perspective. From your application point of view, an email should be considered valid (better, useful) if it can receive mail. That's why all those forums keep sending you activation email :) You should send some random string to every new email address and keep it in a quarantine state until the user can prove he read the secret.
This is because the domain could exist, or even an MX record for that domain can exist in DNS, but neither of these conditions can guarantee that the address is valid - again, when you validate something you are really stating that it can be used later in your code for some purpose, and the purpose for an email address is to receive mail
I don't know if there is an automatically way in Java. But I would lookup for a MX record of the domain. If a MX record exists the domain can potentially get mails.
See also this page for more informations.
Why don't you use InetAddres.getByName on the domain part?
I think there are no exactly effective way to vefy it. all we can do is to vefy the pattern, or more you vefy the mail domain such as hhhgggmail.com. but how could you vefy that "san#hhhgggmail.com do exist" ?
SMTP do has a command 'VEFY' but almost all smtp server doesn't implement this command for security reason.
oh, you want to vefy domain. all smtp server need a mx dns record. you can use dnsjava module to validate it. code as :
public static MXRecord digOptimalMxRecords(String domainName) throws TextParseException {
List<MXRecord> records = DNSHelper.digMxRecords(domainName);
if (CollectionUtils.isNotEmpty(records)) {
Collections.sort(records, new Comparator<MXRecord>() {
#Override
public int compare(MXRecord o1, MXRecord o2) {
return o2.getPriority() - o1.getPriority();
}
});
return records.get(0);
}
return null;
}
public static List<MXRecord> digMxRecords(String domainName) throws TextParseException {
List<MXRecord> list = new ArrayList<MXRecord>();
Lookup mxLookupper = new Lookup(domainName, Type.MX);
mxLookupper.run();
if (mxLookupper.getResult() == Lookup.SUCCESSFUL) {
Record[] answers = mxLookupper.getAnswers();
for (Record record : answers) {
list.add((MXRecord) record);
}
}
return list;
}
Please ignore the variable names as they are unprofessional:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;
public class EmailValidator {
public static void main(String[] args) {
recursion();
}
static void recursion () {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the game of typing a correct email address!");
System.out.println();
System.out.println("As the game says, enter a correct email address.");
System.out.println();
String snow = scanner.nextLine();
String[] sssp = snow.split("#");
if (sssp.length != 2) {
System.out.println();
System.out.println("This is not a correct email address.");
System.out.println();
recursion();
} else {
String regex = "[^a-z0-9._]";
String regex1 = "^\\.|\\.$";
String regex2 = "\s";
String regex3 = "^$";
String regex7 = "\\._|_\\.";
String regex39 = "__";
String regex19 = "\\.\\.";
String regex20 = "^_|_$";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Pattern pattern1 = Pattern.compile(regex1, Pattern.CASE_INSENSITIVE);
Pattern pattern2 = Pattern.compile(regex2, Pattern.CASE_INSENSITIVE);
Pattern pattern3 = Pattern.compile(regex3, Pattern.CASE_INSENSITIVE);
Pattern pattern11 = Pattern.compile(regex7, Pattern.CASE_INSENSITIVE);
Pattern pattern12 = Pattern.compile(regex19, Pattern.CASE_INSENSITIVE);
Pattern pattern13 = Pattern.compile(regex20, Pattern.CASE_INSENSITIVE);
Pattern pattern14 = Pattern.compile(regex39, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(sssp[0]);
Matcher matcher1 = pattern1.matcher(sssp[0]);
Matcher matcher2 = pattern2.matcher(sssp[0]);
Matcher matcher3 = pattern3.matcher(sssp[0]);
Matcher matcher11 = pattern11.matcher(sssp[0]);
Matcher matcher12 = pattern12.matcher(sssp[0]);
Matcher matcher13 = pattern13.matcher(sssp[0]);
Matcher matcher14 = pattern14.matcher(sssp[0]);
boolean matchFound = matcher.find();
boolean matchFound1 = matcher1.find();
boolean matchFound2 = matcher2.find();
boolean matchFound3 = matcher3.find();
boolean matchFound10 = matcher11.find();
boolean matchFound11 = matcher12.find();
boolean matchFound12 = matcher13.find();
boolean matchFound13 = matcher14.find();
String hello = sssp[1];
String[] whoop = hello.split("\\.", 2);
if (whoop.length != 2) {
System.out.println();
System.out.println("This is not a correct email address.");
System.out.println();
recursion();
} else {
String regex4 = "[^a-z]";
String regex5 = "^$";
String regex6 = "\s";
Pattern pattern4 = Pattern.compile(regex4, Pattern.CASE_INSENSITIVE);
Pattern pattern5 = Pattern.compile(regex5, Pattern.CASE_INSENSITIVE);
Pattern pattern6 = Pattern.compile(regex6, Pattern.CASE_INSENSITIVE);
Matcher matcher4 = pattern4.matcher(whoop[0]);
Matcher matcher5 = pattern5.matcher(whoop[0]);
Matcher matcher6 = pattern6.matcher(whoop[0]);
boolean matchFound4 = matcher4.find();
boolean matchFound5 = matcher5.find();
boolean matchFound6 = matcher6.find();
Pattern pattern7 = Pattern.compile(regex4, Pattern.CASE_INSENSITIVE);
Pattern pattern8 = Pattern.compile(regex5, Pattern.CASE_INSENSITIVE);
Pattern pattern9 = Pattern.compile(regex6, Pattern.CASE_INSENSITIVE);
Matcher matcher7 = pattern7.matcher(whoop[1]);
Matcher matcher8 = pattern8.matcher(whoop[1]);
Matcher matcher9 = pattern9.matcher(whoop[1]);
boolean matchFound7 = matcher7.find();
boolean matchFound8 = matcher8.find();
boolean matchFound9 = matcher9.find();
System.out.println();
if(matchFound || matchFound1 || matchFound2 || matchFound3 || matchFound4 || matchFound5 || matchFound6 || matchFound7 || matchFound8 || matchFound9 || matchFound10 || matchFound11 || matchFound12 || matchFound13) {
System.out.println("This is not a correct email address.");
System.out.println();
recursion();
} else {
System.out.println("This is a correct email address.");
System.out.println();
System.out.println("Do you still want to play? (say yes to play) ");
System.out.println();
Scanner scanner1 = new Scanner(System.in);
String snow1 = scanner1.nextLine();
if (snow1.equalsIgnoreCase("yes")) {
System.out.println();
recursion();
} else {
System.out.println();
System.out.println("Okay, then.");
scanner.close();
scanner1.close();
}
}
}
}
}
}