How to use matches method with password validation in Java - java

I am supposed to create a method in a different class that takes a string input and: "validate that a String represents 8 symbols, including letters (upper and lower case), numbers, and special symbols like #$&_."
This is my code so far.
public static boolean validSSN(String SSN)
{
int length = SSN.length();
boolean flag = false;
if(length == 11)
{
if(SSN.matches("^\\d{3}[-]{1}\\d{2}[-]{1}\\d{4}")) flag = true;
}
return flag;
}

I may have found my solution to be:
if(pass.matches("^[A-Z|a-z|0-9|#|$|&|_]{8}")) flag =true;
instead of
if(SSN.matches("^\\d{3}[-]{1}\\d{2}[-]{1}\\d{4}")) flag = true;

Related

Email format type JAVA

I have a task to write a return type method which takes String as an argument and returns boolean. If the String matches with the requirements it returns true else false.
So it should not have any space, and more then 1 '#'and format must be 2>chars#2>chars.2>chars so it should be xyz#xyz.com is true but if any part of it less then 3 it should return to false. I checked so many forums but all i can find regex and we didn't learn anything about it. I could able to do this much but i just couldn't figure out how can i specifically set length of each part and set it as true or false. I'm missing so many and this is all i able to complete;
public static boolean emailAddress(String str) {
if (str.contains(" "))
return false;
boolean flag = true;
if(str3.length()> 11)
for (int i = 0; i < str3.length(); i++) {
for (int j = i + 1; j < str3.length(); j++) {
if (str3.charAt(i) == str3.charAt(j)) {
flag = false;
break;
}
}
if(flag)
return true;
}
return false;
}
This is how I would approach it:
public static boolean isEmailAddress(String str)
{
if(str.trim().equals("")) // Checking if it is an empty string
{
return false;
}
boolean flag = true;
int atIndex = str.indexOf("#"); // Get the index of #
if (atIndex == -1)
{
return false;
}
// Slice your email str and get only the characters before the #
// Check whether the length and the characters are as you want them.
// Do the same thing about the string between # and .
// and then do the same thing about the sliced string after .
}
Check substring() and indexOf().
For anyone who needs it.
This should be one of the Regex to match your requirement:
[a-zA-Z_0-9]{2,}#[a-zA-Z_0-9]{2,}\.[a-zA-Z_0-9]{2,}
[a-zA-Z_0-9] it requires one of the characters, from a-z,A-Z or 0-9
{2,} it requires two or more from one of the characters inside.
A few hints instead of complete solution:
Check if the input string...
has # and . (there could be two or three period's as some domain uses .co.in)
does not have any white spaces (' ')
does not start with special characters ('#', '^')
If possible, do not check for length of each part, as sometimes .in also valid domain.

How to detect if a string contains atleast one char of a particular language?

I am creating an Android application where I have a string. I want to check whether this string contains at least one character that belongs to Hindi language or not.
It does not matter in which language the String is, but if it has atleast one character that is in Hindi language, my function needs to be called.
One of the ways of doing so is comparing each character of the string with all the unicodes of Hindi language. But wont that be too time consuming? For example 50 character of string and 50 unicode will end up with 2500 comparisons already.
What can be the most optimum solution to this?
I think of these two methods
Method 1
boolean isHindi = false;
for (char c: myString.toCharArray()) {
if (Character.UnicodeBlock.of(c) == Character.UnicodeBlock.DEVANAGARI) {
isHindi = true;
break;
}
}
Method 2
boolean isHindi = false;
for (int k = 0; k < Character.codePointCount(myString, 0, myString.length()); k++) {
int c = myString.codePointAt(k);
if (c >= 0x0900 && c <= 0x097F) { //Hindi uni-codes are within this range
isHindi = true;
break;
}
}
If you are using java-8, you could do:
boolean isHindi =
myString.chars().anyMatch(c -> Character.UnicodeBlock.of(c) == Character.UnicodeBlock.DEVANAGARI);
You can also do regex matching. Here is a sample code
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HindiDetctionDemo {
public static void main(String args[]) {
Pattern hindiFirstCharMatchPattern = Pattern.compile("[\\u0900-\\u097F].*");
Matcher hindiFirstCharMatcher = hindiFirstCharMatchPattern.matcher("ok ");
if(hindiFirstCharMatcher.matches()) {
System.out.println("found");
} else {
System.out.println("could not find.");
}
}
}
Note about regex
[\u0900-\u097F] is matcher for hindi characters.
.* is appended so that matching stops after first match.

Validating parts of a string input to make sure letters or numbers are input for certain indexes

Stupid title aside, I'm having trouble validating that the value "MBA222" is not allowed when inputted and values like "MB2222" are. That is to say I'm unsure of how to insure the first two characters of the String are letters and the next four are numbers. Am I perhaps using the wrong method?
public static String getValidMembership(String aMember){
while(isValidMembership(aMember) == false){
aMember = JOptionPane.showInputDialog("Please enter Membership Number");
}
return aMember;
}
private static boolean isValidMembership(String aMember){
boolean result = false;
//TODO add your code here
try{
if(!aMember.substring(0,1).contains("[a-zA-Z]+") &&
!aMember.substring(2,5).contains("[0-9]+")&&
aMember.length() != 6){
result = false;
}
else{
result = true;
}
}catch(Exception e){
result = false;
}
return result;
}
All you need is a single regex:
public static boolean isValidMembership(String aMember) {
return Pattern.matches("^[a-zA-Z]{2}\\d{4}$", aMember);
}
I would recommend reading the Javadoc for the Pattern class which provides a lot of details of how to use regexes.
The String's method contains(...) doesn't work with RegEx, you should use matches(...) for that.
To check if a String matches your criteria, you can use a statement like this:
s.matches("[A-Za-z]{2}\\d{4}")
Here is an elegant and lean implementation of your isValidMembership() method:
private static boolean isValidMembership(String aMember){
if (aMember.replaceFirst("([a-zA-Z]{2}[0-9]{4})", "").length() != 0) {
return false;
}
return true;
}
I removed your try-catch block because it doesn't seem necessary.
This solution uses the following regex, which you can also test by following the link given below:
[a-zA-Z]{2}[0-9]{4}
Regex101
Note that this regex will match two letters followed by four numbers, but the Java code imposes the additional constraint that the length of the string must be 6.

How do I check if one string contains characters from another string?

I want to create a boolean method that allows me to check if the characters in one string randomly generated in a method before contains characters from a string that the user inputs.
Example:
Random base word: Cellphone
User word: Cell --> Yes this is okay.
User word: Cells --> No, it contains letters not found in original word given.
I'm thinking we can maybe do something that looks like this:
public static class boolean usesSymbolsFromWord(String candidate, String base) {
//pseudocode
characters in String candidate are found in String base
return true;
}
return false;
}
Just try it with a build in method of Java.lang.String:
base.contains(candidate);
That's all.
For further informations see the Java Docs:
contains(CharSequence s)
Returns true if and only if this string
contains the specified sequence of char values.
try this func
boolean allS1CharsAreInS2(String s1, String s2) {
for(int i = 0; i < s1.length(); i++) {
char c = s1.charAt(i);
if (s2.indexOf(c) == -1) {
return false;
}
}
return true;
}
I normally use : word1.toUpperCase().contains(word2.toUpperCase()) as I prefer case insensitive check. But its based on your requirement. If it has to be case sensitive checking, you can use word1.contains(word2)

Password Verify

This is the assignment I'm working on right now...
Implement a program that reads in a user password and verifies it meets the following criteria:
Is atleast 8 characters long
Contains atleast 1 lower letter character
Contains atleast 1 upper letter character
Contains atleast 1 numeric digit
Contains atleast 1 special character from the set: !##$%^&*
Does not contain the word “and” or the word “end”
Output a string that prompts the user for a password and include the requirements
above in your output.
Output a string that states valid or invalid. If invalid, state which rule above has not been met.
Utilize the following functionality:
indexOf
Looping structure
charAt()
isDigit()
isUpperCase()
isLowerCase()
and any additional functionality needed
The tricky part to me is that it has to return with all of the things that are missing. Like if I put in a password that says password, it should come back and tell me "you're missing an upper case, a digit, and a special character"
I have a start, but I'm really confused on how to get it to return something to me.
This is what i have so far
/********************************************
This program will test a password for:
8 characters
1 upper case
1 lower case
1 numeric digit
1 special character from the set !##$%^&*
and make sure it doesn't contain AND or END
If the password complies, it will return a valid answer
If not, it will tell the user what they need to do.
*********************************************/
import java.util.Scanner;
public class YoungAmyProg5
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String input;
//input password
System.out.println("Enter a password that follows these rules:\n Is at least 8 characters long\n Contains at least 1 lower case letter\n Contains at least 1 upper case letter\n Contains at least 1 numeric digit\n Contains at least 1 special character from the set: ! ##$%^&*\n Does NOT contain the word "and" or the word "end": ")
input= in.nextLine ();
//Put through string and reply
if
public static boolean isSecurePassword(String password) {
int lengthPassword = password.length();
if (lengthPassword >= 8 ) {
return false;
}
boolean hasUppercase = false; //uppercase
boolean hasLowecase = false; //lowercase
boolean hasDigit = false; //digit
int specialChar = input.indexOf('!', '#', '#', '$', '%', '^', '&', '*'); //special character
int word = input.indexOf ('and', 'end'); //and or end
for (int i = 0; i < lengthPassword; i++) {
char ch = password.charAt(i);
if (Character.isUpperCase(ch) ) {
hasUppercase = true;
}
if (Character.isLowerCase(ch) ) {
hasLowercase = true;
}
if (Character.isDigit(ch) ) {
hasDigit = true;
}
if (specialChar>0) {
specialChar = true;
}
if (word>0) {
word = true;
}
Instead of setting variables, you could also create a list that stores missing things and a boolean too check if error occured:
List<String> missing = new ArrayList<String>();
boolean verified = true;
And inside your if-statements, if somethíng is wrong, set verified to false and add a string like 'an upper case letter' to the list.
if( <password does NOT contain an upper case letter> )
missing.add("an upper case letter");
verified = false;
}
After all if-statements just check if verified is true, if not generate a string and add all strings from the missing list to it. (Generate the sentence)
(I know this will end in a somewhat long code and that it is not too efficient)
Maybe you can think in another way: when you find a reqiurement is violated, return false; if finally turns out no violation, return true.

Categories