Android Email validation: conditions for characters after "." - java

I'm looking to set a validation condition for email whereby after ".xxx" (email termination, e.g: john123#gmail.xxx) the char limit is less than 3 but more than 2 only (e.g: invalid if john123#gmail.c or #gmail.commm).
here is my attempt:
public final boolean validEmail(String target){
boolean valid_dot_com
if(target.toString().contains(".")){
int indexDot = target.toString().indexOf(".");
// substring from char containing "." to last char
String temp = target.toString().substring(indexDot,
target.length());
if(temp.length()<2 && temp.length()>3){
valid_dot_com = false;
}
}
return valid_dot_com && Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
However, this code does not return the result that I needed.
I do have the theory that the Patterns.EMAIL_ADDRESS overwrite my boolean value causing the condition checking to become true even when its not.
Do enlighten me!
Edit:
I've found my answer!
through an online regex generator: https://regex101.com/
I have been able to generate a custom regex pattern to compile and do my validation. Rest of the code is similar to just simple conditions.
Thanks all for the reply!

try this custom pattern
String EMAIL_PATTERN = "^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$";
public final boolean validateEmail(String target) {
if (target !=null && target.length() > 1) {
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(target);
return matcher.matches();
} else if (target.length() == 0) {
return false;
} else {
return false;
}
}

You can use inbuilt fucntion.
if (!Patterns.EMAIL_ADDRESS.matcher(et_email.getText().toString()).matches())
{
your code.
}

Use this:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
Please refer link

try this one validate method
public static final Pattern VALID_EMAIL_ADDRESS_REGEX =
Pattern.compile("^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
public static boolean validate(String emailStr) {
Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr);
return matcher.find();
}

Use this
!TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches()

pass your email string to validate to this function below, and it will return boolean either it is valid or not
public static boolean isEmailValid(String email) {
boolean isValid = false;
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}

The following will validate email.
public static boolean validateEmail(String email) {
Pattern emailPattern = Pattern.compile(".+#.+\\.[a-z]+");
Matcher emailMatcher = emailPattern.matcher(email);
return emailMatcher.matches();
}

Try This One
public final boolean validEmail(String target) {
Log.d("RESULT", "----------------------------------Receieved: " + target);
Log.d("RESULT", "----------------------------------String Length: " + target.length());
Log.d("RESULT", "----------------------------------Index of Dot: " + target.toString().indexOf("."));
boolean valid_dot_com = true;
if (target.toString().contains(".")) {
int indexDot = target.toString().indexOf(".");
// substring from char containing "." to last char
String temp = target.toString().substring(indexDot + 1,
target.length());
Log.d("RESULT", "----------------------------------Sub String : " + temp);
Log.d("RESULT", "----------------------------------Sub String Lenght : " + temp.length());
if ((temp.length() > 3)) {
valid_dot_com = false;
}
}
return valid_dot_com && Patterns.EMAIL_ADDRESS.matcher(target).matches();
}

Already Answered Here
public final static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}

This splits the email string using dot as a delimiter, and gets 2nd string value (at index 1 as it starts from 0) and compares it to check if its 3 or less and greater than 1 after dot.
String st = email.split("\\.")[1];
if(st.length() <=3 && st.length() > 1) {
// its 3 or less but greater than 1 after dot .
}

Related

How to use recursion to check if a string is composed of a pattern?

How can I create a recursive method that takes two parameters, a string and the length of a pattern, and check if the string is composed of repeated occurrences of the given length?
This is what I came up with so far, the code is still incomplete but I don't know what to do next.
public static boolean checkPattern(String str, int pattern) {
if(str.length() % pattern != 0)
return false;
String sub = str.substring(0, pattern);
// if(str.matches(sub)) {
// return checkPattern(str, pattern);
// }
return false;
}
The outpot should be like this:
Enter pattern: abcdabcd 4
abcdabcd is composed of a pattern of length 4.
Enter pattern: abcdabcd 3
abcdabcd is not composed of a pattern of length 3.
Can somebody help me with this problem?
Currently not able to test this but it should be in the Ballpark of what you are trying to archive
public static boolean checkPattern(String str, int patternLength) {
if(str.length() % patternLength != 0)
return false;
if (str.length() == patternLength) {
return true;
}
String sub1 = str.substring(0, patternLength);
String sub2 = str.substring(patternLength, patternLenght * 2);
if(sub1.equals(sub2)) {
return checkPattern(str.substring(patternLength), patternLength);
}
return false;
}

How can I check whether a string contains a given string, that is not a part of another given string?

For instance, I have this string: hello world, you're full of weird things
I'd like to know whether this string contains a ll that's not a part of the string hell, aka it should return true in this example, because there's a ll in the word full;
If the string was only hello world, it wouldn't match, since the ll in hello is a part of the given hell string
Can you try this:
String mainString = "hello world, you're full of weird things";
String findString = "ll";
String removeString = "hell";
String newString = mainString.Remove(mainString.IndexOf(removeString), removeString.Length);
if (newString.Contains(findString))
{
return true;
}
You could use RegExp and Negative Lookbehind:
public static boolean matches(String str) {
final Pattern pattern = Pattern.compile("(?<!he)ll");
Matcher matcher = pattern.matcher(str);
return matcher.find();
}
Test:
System.out.println(matches("hello world, you're full of weird things")); // true
System.out.println(matches("hello world")); // false
regex101.com
public static boolean checkOccurance(String str,String findStr,,String butNotIn ){
int lastIndex = 0;
int count = 0;
str = str.replace(butNotIn,"");
while(lastIndex != -1){
lastIndex = str.indexOf(findStr,lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += findStr.length();
}
}
if(count>1){
return true;
}else{
return false;
}
call the method
System.out.println( checkOccurance("hello world, you're full of weird things","ll","hell"));
output
false
Why not trying to find the boundary (start and end index) of the butNotIn then use String#indexOf until you have an index that is outside the boundary ?
boolean isIn(String string, String word, String butNotIn) {
int start = string.indexOf(butNotIn);
int end = start+butNotIn.length;
int position;
do {
position = string.indexOf(word);
} while (position<start || position>end);
return position>-1;
}

Password Validation regex android

I need to have following password validations :
At least Min Characters 8 and Maximum Characters 15
At least One Number and 1 special characters from (! ##$%^&*-=+?.);
At least One lower case letter
Password shouldn't be sub strings of username and email (min length 3 and max length 15).
Password should be case sensitive.
I have also looked these answers but I am confuse , should I use Input filters to achieve this or Regex?
Any help will be appreciable. It will be great if you guyz provide a working solution.
public class Validation {
public static void main(String[] args) {
String pass = "1AB%CDef555";
String username = "manna";
String email = "mannx#rtt.com";
System.out.println(validiate2(pass, username,email));
}
// if you don't care why it fails and only want to know if valid or not
public static boolean validiate (String pass, String username, String email){
String pattern = "^(?=.*[0-9])(?=.*[a-z])(?=.*[!##$%^&*+=?-]).{8,15}$";
if(pass.matches(pattern)){
for(int i=0;(i+3)<username.length();i++){
if(pass.contains(username.substring(i,i+3)) || username.length()<3 || username.length()>15){
return false;
}
}
for(int i=0;(i+3)<email.length();i++){
if(pass.contains(email.substring(i,i+3)) || email.length()<3 || email.length()>15){
return false;
}
}
return true;
}
return false;
}
// if you want to know which requirement was not met
public static boolean validiate2 (String pass, String username, String email){
if (pass.length() < 8 || pass.length() >15 ){
System.out.println("pass too short or too long");
return false;
}
if (username.length() < 3 || username.length() >15 ){
System.out.println("username too short or too long");
return false;
}
if (!pass.matches(".*\\d.*")){
System.out.println("no digits found");
return false;
}
if (!pass.matches(".*[a-z].*")) {
System.out.println("no lowercase letters found");
return false;
}
if (!pass.matches(".*[!##$%^&*+=?-].*")) {
System.out.println("no special chars found");
return false;
}
if (containsPartOf(pass,username)) {
System.out.println("pass contains substring of username");
return false;
}
if (containsPartOf(pass,email)) {
System.out.println("pass contains substring of email");
return false;
}
return true;
}
private static boolean containsPartOf(String pass, String username) {
int requiredMin = 3
for(int i=0;(i+requiredMin)<username.length();i++){
if(pass.contains(username.substring(i,i+requiredMin))){
return true;
}
}
return false;
}
}
There is great library for that.
It's uses anotations for field and has rich customatization.
I think that #4 still needs to be done by hand but you should definitly check out the library.
Here's the example from github:
#Password(min = 6, scheme = Password.Scheme.ALPHA_NUMERIC_MIXED_CASE_SYMBOLS)
private EditText passwordEditText;
Cheers.
You can try this one:
^(?!.*(user|emailaddress))(?=.*\d)(?=.*[! ##$%^&*=+?.-])(?=.*[a-z]).{8,15}$
Make sure you replace the user and emailaddress by your variable
Explanation
This code works fine for me:
public class NewClass1 {
public static void main(String[] args) {
NewClass1 nc = new NewClass1();
nc.check("abcd123-", "userName", "abc#yahoo.com");
nc.check("userName1-", "userName", "abc#y.c");
nc.check("abc#y.c1b", "userName", "abc#y.c");
nc.check("abcy.c1b", "userName", "abc#y.c");
nc.check("abcd123-", "userName", "abc#yahoo.com");
}
public void check(String string, String userName, String email) {
final String regex = "^(?!.*(" + userName + "|" + email + "))(?=.*\\d)(?=.*[! ##$%^&*=+?.-])(?=.*[a-z]).{8,15}$";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
if (matcher.find()) {
System.out.println(string + "Full match: " + matcher.group(0));
} else {
System.out.println("no match");
}
}
}

How to find and compare all the keyword of a same type in a string

I want to write a method in java to parse a string which is a condition phrase and compare if there is at least one space before and after ALL the logical keyword. for example:
String condition1 = "S(GLHOLD) AND S(GLSHOVE) OR S(PLINK) OR S(PSHARE) AND S(PSTT) AND S(PNET)"
String condition2 = "S(GLHOLD) AND S(GLSHOVE) OR S(PLINK)OR S(PSHARE) AND S(PSTT) AND S(PNET)"
String condition3 = "S(GLHOLD) ANDS(GLSHOVE) OR S(PLINK) OR S(PSHARE) AND S(PSTT) AND S(PNET)"
Here condition1 is good but 2 and 3 are not since they have missing space. How can I achieve this?
If you're just looking for "condition is ok" or not, then it's just this code:
private static boolean spacesEverywhere(String condition) {
return !condition.toUpperCase().matches(".*((AND|OR)\\S+|\\S+(AND|OR)).*");
}
The regular expression searches for AND, OR with non-whitespace before or behind it (or both).
Additionally:
If you want to know, at which position the missing space is, I would split with "(AND|OR)" as regular expression and check each string in the resulitng array if it starts or end with a non-whitespace character.
If the condition itself could contain AND or OR, like such a condition: "S(GLH**OR**D) AND S(GLSHOVE)" then I would try ANTLR
Using regex, this works:
public static boolean containsSeparated(String condition, List<String> keywords) {
for (String word : keywords) {
Pattern p = Pattern.compile("\\S" + word + "|" + word + "\\S");
Matcher matcher = p.matcher(condition);
boolean foundNotSeparated = matcher.find();
if (foundNotSeparated) {
return false;
}
}
return true;
}
\S is not-whitespace, so exactly what you need to find to mark input as invalid, and it should be searched in both begin and end of given word
Test:
public static void main(String[] args) {
String condition1 = "S(GLHOLD) AND S(GLSHOVE) OR S(PLINK) OR S(PSHARE) AND S(PSTT) AND S(PNET)";
String condition2 = "S(GLHOLD) AND S(GLSHOVE) OR S(PLINK)OR S(PSHARE) AND S(PSTT) AND S(PNET)";
String condition3 = "S(GLHOLD) ANDS(GLSHOVE) OR S(PLINK) OR S(PSHARE) AND S(PSTT) AND S(PNET)";
List<String> shuoldBeSeparated = Arrays.asList("OR", "AND");
System.out.println(containsSeparated(condition1, shuoldBeSeparated));
System.out.println(containsSeparated(condition2, shuoldBeSeparated));
System.out.println(containsSeparated(condition3, shuoldBeSeparated));
System.out.println(containsSeparated("A AND B ORCC", shuoldBeSeparated));
System.out.println(containsSeparated("A AND D", shuoldBeSeparated));
System.out.println(containsSeparated("A AND B OR C", shuoldBeSeparated));
}
public static boolean containsSeparated(String condition, List<String> keywords) {
for (String word : keywords) {
Pattern p = Pattern.compile("\\S" + word + "|" + word + "\\S");
Matcher matcher = p.matcher(condition);
boolean foundNotSeparated = matcher.find();
if (foundNotSeparated) {
return false;
}
}
return true;
}
prints:
true
false
false
false
true
true
Your answer will be similar to this:
private static boolean isValid(final String condition)
{
String[] splitValues = condition.split("AND|OR");
if (!splitValues[0].endsWith(" "))
{
return false;
}
if (!splitValues[(splitValues.length - 1)].startsWith(" "))
{
return false;
}
for (int index = 1; index < (splitValues.length - 1); ++index)
{
if (!splitValues[index].startsWith(" "))
{
return false;
}
if (!splitValues[index].endsWith(" "))
{
return false;
}
}
return true;
}
Split the string using AND and OR as the seperators. between every string and every seperator, there must be at least one space character or the string is formatted incorrectly.

How to check if a string can be exhausted by regex matches?

So the problem is to determine if every character in a string would be included in a match of a particular regex. Or, to state it differently, if the set of all of the character positions that could be included in some match of a particular regex includes all the character positions in the string.
My thought is to do something like this:
boolean matchesAll(String myString, Matcher myMatcher){
boolean matched[] = new boolean[myString.size()];
for(myMatcher.reset(myString); myMatcher.find();)
for(int idx = myMatcher.start(); idx < myMatcher.end(); idx++)
matched[idx] = true;
boolean allMatched = true;
for(boolean charMatched : matched)
allMatched &= charMatched;
return allMatched
}
Is there a better way to do this, however?
Also, as I was writing this, it occured to me that that would not do what I want in cases like
matchesAll("abcabcabc", Pattern.compile("(abc){2}").matcher()); //returns false
because Matcher only tries to match starting at the end of the last match. I want it to return true, because if you start the matcher at position 3, it could include the third abc in a match.
boolean matchesAll(String myString, Matcher myMatcher){
boolean matched[] = new boolean[myString.size()];
boolean allMatched = true;
for(int idx = 0; idx < myString.size() && myMatcher.find(idx);
idx = myMatcher.start() + 1) {
for(int idx2 = myMatcher.start(); idx2 < myMatcher.end(); idx2++)
matched[idx2] = true;
}
boolean allMatched = true;
for(boolean charMatched : matched)
allMatched &= charMatched;
return allMatched;
}
Is there any way to make this code better, faster, or more readable?
I have 2 answers for you, although I am not sure I understand the question right.
Call Pattern.matcher(str2match).matches() method instead of find(). In one shot a true return value will tell you if the entire string is matched.
Prepend the reg exp by "^" (beginning of string) and add a "$" at the end (for end of string) before "Pattern.compile(str)"-ing the regex.
The 2 solutions can go together, too. An example class follows - you can copy it into AllMatch.java, compile it with "javac AllMatch.java" and run it as "java AllMatch" (I assume you have "." in your CLASSSPATH). Just pick the solution you find is more elegant :) Happy New Year!
import java.util.regex.Pattern;
public class AllMatch {
private Pattern pattern;
public AllMatch (String reStr) {
pattern = Pattern.compile ("^" + reStr + "$");
}
public boolean checkMatch (String s) {
return pattern.matcher(s).matches();
}
public static void main (String[] args) {
int n = args.length;
String rexp2Match = (n > 0) ? args[0] : "(abc)+",
testString = (n > 1) ? args[1] : "abcabcabc",
matchMaker = new AllMatch (rexp2Match)
.checkMatch(testString) ? "" : "un";
System.out.println ("[AllMatch] match " + matchMaker +
"successful");
}
}
This works:
private static boolean fullyCovered(final String input,
final Pattern pattern)
{
// If the string is empty, check that it is matched by the pattern
if (input.isEmpty())
return pattern.matcher(input).find();
final int len = input.length();
// All initialized to false by default
final boolean[] covered = new boolean[len];
final Matcher matcher = pattern.matcher(input);
for (int index = 0; index < len; index++) {
// Try and match at this index:
if (!matcher.find(index)) {
// if there isn't a match, check if this character is already covered;
// if no, it's a failure
if (!covered[index])
return false;
// Otherwise, continue
continue;
}
// If the match starts at the string index, fill the covered array
if (matcher.start() == index)
setCovered(covered, index, matcher.end());
}
// We have finished parsing the string: it is fully covered.
return true;
}
private static void setCovered(final boolean[] covered,
final int beginIndex, final int endIndex)
{
for (int i = beginIndex; i < endIndex; i++)
covered[i] = true;
}
It will probably not be any faster to execute, but I surmise it is easier to read ;) Also, .find(int) resets the matcher, so this is safe.

Categories