How can I get TextField input by using ArrayList - java

I need to test a method that takes an input TextFild, how can I change the input to ArrayList to get the data. I am getting an error that says
java.lang.ClassCastException: class java.lang.Character cannot be cast to class
private boolean validatePassword() {
Pattern p = Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,15})");
Matcher matcher = p.matcher(passwordField.getText());
if (matcher.matches()) {
return true;
} else {
lblMessage.setText("Please enter a valid password \n" +
"(at least one uppercase, lowercase and 8 or more characters ");
return false;
}
}
my solution
public class TestCases {
ArrayList<Character> characters = new ArrayList<>();
public boolean validatePassword() {
Pattern p = Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,15})");
for (int i = 0; i < characters.size(); i++) {
Object j = characters.get(i);
Matcher matcher = p.matcher((CharSequence) j);
if (matcher.matches()) {
return true;
} else {
System.out.println(
"Please enter a valid password \n" +
"(at least one uppercase, lowercase and 8 or more characters "););
return false;
}
}
return false;
}
public void setEmail(ArrayList<Character> list) {
characters = list;
}
}
Junit class
#Test
void test() {
String password= "Kd123456";
ArrayList<Character> paswordField=new ArrayList<>();
for(int i= 0 ; i<password.length(); i++){
paswordField.add(password.charAt(i));
}
TestCases valid= new TestCases();
valid.setEmail(paswordField);
assertEquals(true,valid.validatePassword());
}
}

if hope this will help you !!
import static org.junit.Assert.assertEquals;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
public class TestCases {
public boolean validatePassword(String s) {
Pattern p = Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-z0-9 ]).{8,15})",
Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(s);
if (matcher.matches()) {
return true;
} else {
System.out.println("Please enter a valid password \n"
+ "(at least one uppercase, lowercase and 8 or more characters ");
return false;
}
}
#Test
public void test() {
String password = "Kd12#3456";
TestCases valid = new TestCases();
assertEquals(true, valid.validatePassword(password));
}
}

Related

How to get a count of exact double six repeated in a string (6678766566) in java?

I'm unable to build a logic to get a count of double six which present in a string.
For example '6678766566' there are three double sixes present in this string.
There can be many ways to do so. Some of the ways are shown below:
Using the RegEx pattern, 6(?=6) and Java Regex API:
Stream version:
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
long count66 = Pattern.compile("6(?=6)")
.matcher("6678766566")
.results()
.count();
System.out.println(count66);
}
}
Non-Stream version:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
int count66 = 0;
Matcher matcher = Pattern.compile("6(?=6)").matcher("6678766566");
while (matcher.find()) {
count66++;
}
System.out.println(count66);
}
}
Note that (?=(regex)) is used for Positive Lookahead.
Using String#indexOf:
public class Main {
public static void main(String[] args) {
int count66 = 0;
String str = "6678766566";
for (int i = 0; i < str.length(); i++) {
int index = str.indexOf("66", 0);
if (index != -1) {
count66++;
str = str.substring(index + 1);
}
}
System.out.println(count66);
}
}
String str = "6678766566";
int count = 0;
for(int i=0; i<str.length()-1; i++){
if(str.charAt(i)=='6' && str.charAt(i+1)=='6'){
count++;
i++;
}
}
System.out.println(count);
To make it a little interesting, you could use the RegEx way. Note, we are not doing any Overlaps.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Match {
public static void main(String[] args) {
final String regex = "(66)";
final String string = "667876656666";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
//prints 4
System.out.println("Number of matches: " + matcher.results().count());
}
}
To include overlaps as well:
final String string = "667876656666767666";
int i = 0;
int count = 0;
while (i < string.length() -1) {
if (string.charAt(i) == '6' && string.charAt(i+1) == '6') {
count++;
}
i++;
}
// prints 7
System.out.println("Number of matches including overlaps: " + count);
You can use Pattern api:
String s = "6678766766";
Pattern p = Pattern.compile("66");
Matcher m = p.matcher(s);
int count = 0;
while(m.find()) {
count++;
}
System.out.println(count);
Note: to include overlaps use pattern (6)(?=(6)). This will give count 2 for 666.

Find first alphabetic char and replace it to uppercase char [duplicate]

This question already has answers here:
How to get position of the first letter in a string [closed]
(3 answers)
Closed 3 years ago.
public String setPassword(String username) {
int passl = 8;
String s = username;
if(s.length()<passl) {
s+="*";
}
if(s.length()>passl) {
s=s.substring(0,passl);
}
return s.replaceAll( "[aeiou]", "*" );
}
I have this code. When it gets a username it replaces all vowels to * and now I need to replace first found alphabetic char to uppercase char. Like username is AdrianDe and it must return something like this *Dr**nD*
Here is the missing part:
String result = s.replaceAll("(?i)[aeiou]", "*"); // (?i) for case insensitive
Pattern pattern = Pattern.compile("([a-zA-Z])"); // any character
Matcher matcher = pattern.matcher(result);
if(matcher.find()){
result = matcher.replaceFirst(matcher.group(0).toUpperCase());
}
Full method:
public String setPassword(String username) {
int passl = 8;
String s = username;
if (s.length() < passl) {
s += "*";
}
if (s.length() > passl) {
s = s.substring(0, passl);
}
s = s.replaceAll("(?i)[aeiou]", "*"); // (?i) for case insensitive
Pattern pattern = Pattern.compile("([a-zA-Z])"); // any character
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
s = matcher.replaceFirst(matcher.group(0).toUpperCase());
}
return s;
}
You can do it as follows:
public class New {
public static void main(String[] args) {
String username="AdrianDe";
System.out.println(setPassword(username));
System.out.println(firstLetterCap(setPassword(username)));
}
static String setPassword(String username) {
int passl = 8;
String s = username;
if(s.length()<passl) {
s+="*";
}
if(s.length()>passl) {
s=s.substring(0,passl);
}
return s.replaceAll( "[AEIOUaeiou]", "*" );
}
static String firstLetterCap(String s) {
int i;
StringBuffer sb=new StringBuffer();
for (i = 0; i < s.length(); i++) {
if (Character.isLetter(s.charAt(i)))
break;
sb.append(s.charAt(i));
}
sb.append((char)(s.charAt(i)-32));
sb.append(s.substring(i+1,s.length()));
return sb.toString();
}
}
Output:
*dr**nD*
*Dr**nD*

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");
}
}
}

Java Pattern/Matcher - Return the matches from one method to another

I'm an absolute Java beginner. I've searched on the forums, but couldn't find an answer to this question.
I have two classes, one which browses through an arraylist of sentences. I only attach the for-each loop as seen below.
"matching" is the instance of the other class (containing the pattern/matcher code)
matchEndings is the method, attached below.
for (String sentence: sentences) {
String match = matching.matchEndings(sentence);
if (match.length() > 0) {
System.out.println(match);
}
}
This is the method.
public String matchEndings(String s){
Pattern p = Pattern.compile(".*?(aa|ee)");
Matcher m = p.matcher(s);
return m.group();
}
My question is, how do I return the matched sentences, containing aa / ee endings, to the first class, and have it printed there? The code is compiled, but when I run I get
Exception in thread "main" java.lang.IllegalStateException: No match found
at java.util.regex.Matcher.group(Unknown Source)
at java.util.regex.Matcher.group(Unknown Source)
Thank you so much in advance!
Matcher.group() only returns if there is a match already. You need to do something like this:-
if (m.matches()) {
return m.group();
} else {
return "";
}
It seems like overkill to use RegEx when all you need is a simple endsWith(String):
public void print(final List<String> sentences, final String... endings){
for(final String sentence : sentences){
for(final String ending : endings){
if(sentence.endsWith(ending)){
System.out.println(sentence);
break;
}
}
}
}
The method above will loop through a List<String> of sentences and print out all of the sentences that end with one of the elements in endings. For usage, you could try:
print(sentences, "aa", "ee");
Where sentences is your ArrayList<String> of sentences.
The matches or find methods must precede the group method. Since matches attempts to match the entire region against the pattern, it is more appropriate here
public String matchEndings(String s){
Pattern p = Pattern.compile("(aa|ee)$");
Matcher m = p.matcher(s);
if (m.matches) {
return m.group();
} else {
return ""
}
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PotenssienSumma {
public static void main(String[] args) {
ArrayList<String> sentences = new ArrayList<>(10);
sentences.add("aa");
sentences.add("1324");
for (String sentence: sentences) {
String match = Matching.matchEndings(sentence);
if (match.length() > 0) {
System.out.println(match);
}
}
}
}
class Matching{
public static String matchEndings(String s){
Pattern p = Pattern.compile(".*?(aa|ee)");
Matcher m = p.matcher(s);
if (m.matches()) {
return m.group();
} else {
return "";
}
}
}
Don't construct Pattern in the method. That is expensive. Put the pattern object into a static final variable.
The correct use for patterns is the following:
while(matcher.find()) {
sysout(matcher.group());
}
This will print all matches, if you want just one match, replace the while with if.
I don't know if this is intentional but your regex doesn't match ee|aa to end of the string. It matches ee or aa anywhere in the string along with any characters preceeding it. For instance for string Fox preens in front of a vixen your regex returns string Fox pree. Don't know if that's intended.
Here's a class that takes a list or a collection of strings as an argument and then lazily finds all words that end in aa or ee. It has a main method you can run to test.
public class Endings implements Iterable<String> {
private final Iterable<String> strings;
private static final Pattern pat = Pattern.compile("(?<=^|\\s)\\S*(aa|ee)(?=\\s|$)");
public static void main(String[] args) {
Endings endings = new Endings(Arrays.asList("This testaabb testee testaa", "Test2aa Test3ee ", "no match"));
for(String word : endings) {
System.out.println(word);
}
}
public Endings(Iterable<String> strings) {
this.strings = strings;
}
public Iterator<String> iterator() {
return new Iterator<String>() {
private Iterator<String> iter = strings.iterator();
private Matcher m;
private String result;
public boolean hasNext() {
if (result == null) {
if (m == null) {
if (iter.hasNext()) {
m = pat.matcher(iter.next());
} else {
return false;
}
}
if (m.find()) {
result = m.group();
return true;
} else {
m = null;
return hasNext();
}
} else {
return true;
}
}
public String next() {
if (result != null) {
String ret = result;
result = null;
return ret;
} else {
throw new NoSuchElementException();
}
}
public void remove() {
}
};
}
}

How can I find whitespace in a String?

How can I check to see if a String contains a whitespace character, an empty space or " ". If possible, please provide a Java example.
For example: String = "test word";
For checking if a string contains whitespace use a Matcher and call its find method.
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();
If you want to check if it only consists of whitespace then you can use String.matches:
boolean isWhitespace = s.matches("^\\s*$");
Check whether a String contains at least one white space character:
public static boolean containsWhiteSpace(final String testCode){
if(testCode != null){
for(int i = 0; i < testCode.length(); i++){
if(Character.isWhitespace(testCode.charAt(i))){
return true;
}
}
}
return false;
}
Reference:
Character.isWhitespace(char)
Using the Guava library, it's much simpler:
return CharMatcher.WHITESPACE.matchesAnyOf(testCode);
CharMatcher.WHITESPACE is also a lot more thorough when it comes to Unicode support.
This will tell if you there is any whitespaces:
Either by looping:
for (char c : s.toCharArray()) {
if (Character.isWhitespace(c)) {
return true;
}
}
or
s.matches(".*\\s+.*")
And StringUtils.isBlank(s) will tell you if there are only whitepsaces.
Use Apache Commons StringUtils:
StringUtils.containsWhitespace(str)
public static void main(String[] args) {
System.out.println("test word".contains(" "));
}
You could use Regex to determine if there's a whitespace character. \s.
More info of regex here.
Use this code, was better solution for me.
public static boolean containsWhiteSpace(String line){
boolean space= false;
if(line != null){
for(int i = 0; i < line.length(); i++){
if(line.charAt(i) == ' '){
space= true;
}
}
}
return space;
}
You can use charAt() function to find out spaces in string.
public class Test {
public static void main(String args[]) {
String fav="Hi Testing 12 3";
int counter=0;
for( int i=0; i<fav.length(); i++ ) {
if(fav.charAt(i) == ' ' ) {
counter++;
}
}
System.out.println("Number of spaces "+ counter);
//This will print Number of spaces 4
}
}
String str = "Test Word";
if(str.indexOf(' ') != -1){
return true;
} else{
return false;
}
Maybe I'm late with the most updated answer. You can use one of the following solution:
public static boolean containsWhiteSpace(final String input) {
if (isNotEmpty(input)) {
for (int i = 0; i < input.length(); i++) {
if (Character.isWhitespace(input.charAt(i)) || Character.isSpaceChar(input.charAt(i))) {
return true;
}
}
}
return false;
}
or
public static boolean containsWhiteSpace(final String input) {
return CharMatcher.whitespace().matchesAnyOf(input);
}
import java.util.Scanner;
public class camelCase {
public static void main(String[] args)
{
Scanner user_input=new Scanner(System.in);
String Line1;
Line1 = user_input.nextLine();
int j=1;
//Now Read each word from the Line and convert it to Camel Case
String result = "", result1 = "";
for (int i = 0; i < Line1.length(); i++) {
String next = Line1.substring(i, i + 1);
System.out.println(next + " i Value:" + i + " j Value:" + j);
if (i == 0 | j == 1 )
{
result += next.toUpperCase();
} else {
result += next.toLowerCase();
}
if (Character.isWhitespace(Line1.charAt(i)) == true)
{
j=1;
}
else
{
j=0;
}
}
System.out.println(result);
Use org.apache.commons.lang.StringUtils.
to search for whitespaces
boolean withWhiteSpace = StringUtils.contains("my name", " ");
To delete all whitespaces in a string
StringUtils.deleteWhitespace(null) = null
StringUtils.deleteWhitespace("") = ""
StringUtils.deleteWhitespace("abc") = "abc"
StringUtils.deleteWhitespace(" ab c ") = "abc"
I purpose to you a very simple method who use String.contains:
public static boolean containWhitespace(String value) {
return value.contains(" ");
}
A little usage example:
public static void main(String[] args) {
System.out.println(containWhitespace("i love potatoes"));
System.out.println(containWhitespace("butihatewhitespaces"));
}
Output:
true
false
package com.test;
public class Test {
public static void main(String[] args) {
String str = "TestCode ";
if (str.indexOf(" ") > -1) {
System.out.println("Yes");
} else {
System.out.println("Noo");
}
}
}

Categories