I am new to android studio and kotlin. I need to find a way to check if a string contains a char, which is, in this case, "/"
I want to form a piece of code in the following manner:
if (string input contains a character "/") = true {
<code>
}
else{
<code>
}
Please tell me how to do this, and if possible, give me the code I'll need to specify as the condition.
You can use contains, like this:
val a = "hello/"
val b = a.contains("/")
When the string has the character will return true.
Here is my code .This doesn't work
button1.getText() + button2.getText() == button3.getText()
Use equals to compare strings,
Try this,
String button1Text = button1.getText().toString();
String button2Text = button2.getText().toString();
String button3Text = button3.getText().toString();
if((button1Text + button2Text).equals(button3Text)){
// strings are equal
} else {
// strings are not equal
}
button[6].getText().toString().equals(button[0].getText().toString().concat(button[3].getText().toString()));
When you work with Strings in Java the operator == checks if the two objects refer to the same instance of an object.
While equals() checks if the two objects are actually equivalent, even if they are not the same instance.
try:
String button1Text = button1.getText().toString();
String button2Text = button2.getText().toString();
String button3Text = button3.getText().toString();
if (button1Text.equals(button3) && button2Text.equals(button3)) {
// do something...
} else {
// do something...
}
I am trying to ignore spaces in editview between text, I am not quite sure how I can go about doing this. I know I can use trim feature to ignore spaces before and after the full text but how do I ignore space between strings if there is any;
String myTextEdited myText.getText().toString().trim();
For example, if I have / user types in this;
Allan Bob
3523 JKO
NY1 U90
I want to ingore spaces when I read this in my if statement or put it in another variable for example;
String name = "AllanBob"
For example, to ignore upper and lower cases I am doing this;
if (myText.getText().toString().trim().equalsIgnoreCase(userInput)) {
// do something
} else {
// do something
}
What I would like to do is add another feature in here that also ignores spaces before, between and after text e.g. instead of;
myname is Henry . (space until here)
It should read it as mynameishenry but to the user it still appears as they have written it.
Please let me know if my question was not clear, I will try explaining it better
EDITED:
is it possible to ignore spaces in string that I have inside my if statement. For example;
if (myText.getText().toString().trim().equalsIgnoreCase("Henry 0887")) {
// do something
} else {
// do something
}
but currently if the user types in henry0887, the if statement does not validate it because I added a space inside my validation text and therefoe its looking for a space in the text, is it possible to over come this, so even if I have space inside my validation it ignores it.
Did you try this:
String myString = myEditText.getText().toString();
myString = myString .replace(" ", "");
Hope it helps
EDIT:
if (myText.getText().toString().replace(" ", "").equalsIgnoreCase(userInput) || myText.getText().toString().equalsIgnoreCase(userInput)) {...
Try this,
if(myText.getText().toString().trim().replace(" ","").equalsIgnoreCase(userInput)) {
// do something
} else {
// do something
}
Hope this helps.
use replaceAll() method.
str = str.replace(" ","");
or for all space chars:
str = str.replace("\\s+","");
EDIT
if (myText.getText().toString().replace("\\s+","").equalsIgnoreCase(userInput)) {
// do something
} else {
// do something
}
EDIT2
if (myText.getText().toString().replace("\\s+","").equalsIgnoreCase("Henry 0887".replace("\\s+",""))) {
// do something
} else {
// do something
}
How can i validating the EditText with Regex by allowing particular characters .
My condition is :
Password Rule:
One capital letter
One number
One symbol (#,$,%,&,#,) whatever normal symbols that are acceptable.
May I know what is the correct way to achieve my objective?
Try this may helps
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{4,}$
How it works?
^ # start-of-string
(?=.*[0-9]) # a digit must occur at least once
(?=.*[a-z]) # a lower case letter must occur at least once
(?=.*[A-Z]) # an upper case letter must occur at least once
(?=.*[##$%^&+=]) # a special character must occur at least once you can replace with your special characters
(?=\\S+$) # no whitespace allowed in the entire string
.{4,} # anything, at least six places though
$ # end-of-string
How to Implement?
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = (EditText) findViewById(R.id.edtText);
Button btnCheck = (Button) findViewById(R.id.btnCheck);
btnCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (isValidPassword(editText.getText().toString().trim())) {
Toast.makeText(MainActivity.this, "Valid", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "InValid", Toast.LENGTH_SHORT).show();
}
}
});
}
public boolean isValidPassword(final String password) {
Pattern pattern;
Matcher matcher;
final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{4,}$";
pattern = Pattern.compile(PASSWORD_PATTERN);
matcher = pattern.matcher(password);
return matcher.matches();
}
}
And for the Kotlin lovers :
fun isValidPassword(password: String?) : Boolean {
password?.let {
val passwordPattern = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{4,}$"
val passwordMatcher = Regex(passwordPattern)
return passwordMatcher.find(password) != null
} ?: return false
}
None of the above worked for me.
What worked for me:
fun isValidPasswordFormat(password: String): Boolean {
val passwordREGEX = Pattern.compile("^" +
"(?=.*[0-9])" + //at least 1 digit
"(?=.*[a-z])" + //at least 1 lower case letter
"(?=.*[A-Z])" + //at least 1 upper case letter
"(?=.*[a-zA-Z])" + //any letter
"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=\\S+$)" + //no white spaces
".{8,}" + //at least 8 characters
"$");
return passwordREGEX.matcher(password).matches()
}
Source: Coding in Flow
Hope it helps someone.
Try this.
(/^(?=.*\d)(?=.*[A-Z])([#$%&#])[0-9a-zA-Z]{4,}$/)
(/^
(?=.*\d) //should contain at least one digit
(?=.*[#$%&#]) //should contain at least one special char
(?=.*[A-Z]) //should contain at least one upper case
[a-zA-Z0-9]{4,} //should contain at least 8 from the mentioned characters
$/)
try {
if (subjectString.matches("^(?=.*[#$%&#_()=+?»«<>£§€{}\\[\\]-])(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).*(?<=.{4,})$")) {
// String matched entirely
} else {
// Match attempt failed
}
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
(?=.*[#\$%&#_()=+?»«<>£§€{}.[\]-]) -> must have at least 1 special character
(?=.*[A-Z]) -> Must have at least 1 upper case letter
(?=.*[a-z]) -> Must have at least 1 lower case letter
(?=.*\\d) -> Must have at least 1 digit
(?<=.{4,})$") -> Must be equal or superior to 4 chars.
As an addition to the answers already given, I would suggest a different route for identifying special characters and also would split up the check for the different rules.
First splitting it up: Instead of making one big rule, split it and check every rule separately, so that you are able to provide feedback to the user as to what exactly is wrong with his password. This might take a bit longer but in something like a password checkup this will not be noticable. Also, this way the conditions are more readable.
Secondly, instead of checking for a list of special characters, you could flip it and check if the password contains any characters that are neither letters of the latin alphabet (a-zA-Z) nor digits (0-9). That way you don't "forget" special characters. For example, lets say you check specifically but in your check you forget a character like "{”. With this approach, this can't happen. You can extend that list by things you don't consider to be special characters explicitly, for example a space. In kotlin, it would look like this:
val errorText = when {
/* Rule 1 */
!password.contains(Regex("[A-Z]")) -> "Password must contain one capital letter"
/* Rule 2 */
!password.contains(Regex("[0-9]")) -> "Password must contain one digit"
/* Rule 3, not counting space as special character */
!password.contains(Regex("[^a-zA-Z0-9 ]")) -> "Password must contain one special character"
else -> null
}
Depending on your encoding, you can also use regex and define your special characters using ranges of hex codes like
Reges("[\x00-\x7F]")
I'm too late to answer but still it may help you.
I've worked with Kotlin.
Add following function.
private fun isValidPassword(password: String): Boolean {
val pattern: Pattern
val matcher: Matcher
val specialCharacters = "-#%\\[\\}+'!/#$^?:;,\\(\"\\)~`.*=&\\{>\\]<_"
val PASSWORD_REGEX = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[$specialCharacters])(?=\\S+$).{8,20}$"
pattern = Pattern.compile(PASSWORD_REGEX)
matcher = pattern.matcher(password)
return matcher.matches()
}
Function description:
(?=.*[0-9]) # a digit must occur at least once
(?=.*[a-z]) # a lower case letter must occur at least once
(?=.*[A-Z]) # an upper case letter must occur at least once
(?=.[-#%[}+'!/#$^?:;,(")~`.=&{>]<_]) # a special character must occur at least once
replace with your special characters
(?=\S+$) # no whitespace allowed in the entire string .{8,} #
anything, at least six places though
You can modify it as needed.
Hope it helps.
you can use the class Patern than Matcher for every checking format.
I give you an exemple of use :
Pattern pattern = Pattern.compile(".+#.+\\.[a-z]+");
Matcher matcher = pattern.matcher(myEmailString);
if (!myEmailString.contains("#") || !matcher.matches()) {
// error in the email : do staff
myEmailView.setError("invalid email !");
}
All of the other answers are good, but the implementation of special characters were a bit too messy for my taste. I used Unicode for special characters instead.
I used special characters specified in the OWASP website.
Kotlin:
val SPECIAL_CHARACTERS_REGEX =
"?=.*[\\u0020-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]"
val PASSWORD_REGEX =
"^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])($SPECIAL_CHARACTERS_REGEX).{8,}\$"
fun isValidPassword(password: String) = Pattern.matches(PASSWORD_REGEX, password)
Most common password validation is
At least 8 character
Require numbers
Require special character
Require uppercase letters
Require lowercase letters
Regex:
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[\\\/%§"&“|`´}{°><:.;#')(#_$"!?*=^-]).{8,}$
Kotlin code:
val PASSWORD_REGEX_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[\\\/%§"&“|`´}{°><:.;#')(#_$"!?*=^-]).{8,}$"
fun isValidPassword(password: String?): Boolean {
val pattern: Pattern =
Pattern.compile(PASSWORD_REGEX_PATTERN)
val matcher: Matcher = pattern.matcher(password)
return matcher.matches()
}
online regex validator to check it:
https://regex101.com/
https://www.freeformatter.com/java-regex-tester.html#ad-output
private fun passwordValidate(password1: String, password2: String): Boolean {
when {
password1.length < 9 -> {
textView2.text = "Password Has To Be At Least 9 Characters Long"
return false
}
!password1.matches(".*[A-Z].*".toRegex()) -> {
textView2.text = "Password Must Contain 1 Upper-case Character"
return false
}
!password1.matches(".*[a-z].*".toRegex()) -> {
textView2.text = "Password Must Contain 1 Lower-case Character"
return false
}
!password1.matches(".*[!##$%^&*+=/?].*".toRegex()) -> {
textView2.text = "Password Must Contain 1 Symbol"
return false
}
password1 != password2 -> {
textView3.text = "Passwords Don't Match"
return false
}
else -> return true
Try this,
if (validatePassword())
{
// if valid
}
private boolean validatePassword() {
String passwordInput = password.getText().toString().trim();
if (!passwordInput.matches(".*[0-9].*")) {
Toast.makeText(mActivity, "Password should contain at least 1 digit", Toast.LENGTH_SHORT).show();
return false;
}
else if (!passwordInput.matches(".*[a-z].*")) {
Toast.makeText(mActivity, "Password should contain at least 1 lower case letter", Toast.LENGTH_SHORT).show();
return false;
}
else if (!passwordInput.matches(".*[A-Z].*")) {
Toast.makeText(mActivity, "Password should contain at least 1 upper case letter", Toast.LENGTH_SHORT).show();
return false;
}
else if (!passwordInput.matches(".*[a-zA-Z].*")) {
Toast.makeText(mActivity, "Password should contain a letter", Toast.LENGTH_SHORT).show();
return false;
}
else if (!passwordInput.matches( ".{8,}")) {
Toast.makeText(mActivity, "Password should contain 8 characters", Toast.LENGTH_SHORT).show();
return false;
}
else {
return true;
}
}
I have a simple way to check it without using regex in Kotlin.
It will check for password length >= 8, at least one capital letter, one small letter, one number, and one special character.
fun isValidPassword(pass:String):Boolean{
if(pass.length<8) return false
var u = 0
var l = 0
var d = 0
var s = 0
for (char in pass){
if(char.isUpperCase()) u++
else if(char.isLowerCase()) l++
else if(char.isDigit()) d++
else if(char in "##$%^&+=_.") s++
}
if(u==0|| l==0 || s==0 || d==0) return false
return true
}
I have this code :
String[] whereyoufromarray = {"where", "you", "from"};
for (String whereyoufromstring : whereyoufromarray)
{
if (value.contains(whereyoufromstring)) {
//statement
}
}
But I want that if to only execute the statement if "value" has all of the words included in the array, something like "where are you from?". Currently if value has ONLY one of the words in the array the statement is executed.
I can do this with if (value.contains("where") && value.contains("you") && value.contains ("from")) but this just seems unnecessarily long. There has to be a workaround using arrays that I am missing.
Well, what is it?
p.s.: sorry for poor grammar. i'm suffering from sleep deprivation.
String[] whereyoufromarray = {"where", "you", "from"};
boolean valueContainsAllWordsInArray = true;
for (String whereyoufromstring : whereyoufromarray) {
// If one word wasn't found, the search is over, break the loop
if(!valueContainsAllWordsInArray) break;
valueContainsAllWordsInArray = valueContainsAllWordsInArray &&
value.contains(whereyoufromstring);
}
// valueContainsAllWordsInArray is now assigned to true only if value contains
// ALL strings in the array
For a case like this, I typically implement a function just to make the test. Let's call it containsAll()
public static boolean containsAll(String[] strings, String test)
{
for (String str : strings)
if (!test.contains(str))
return false;
return true;
}
And now you just do
if (containsAll(whereyoufromarray, value))
//statement
String[] whereyoufromarray = {"where", "you", "from"};
int arrayLength = whereyoufromarray.length;
int itemCount = 0;
for(String whereyoufromstring : whereyoufromarray)
{
if(value.contains(whereyoufromstring))
{
itemCount++;
}
}
if (itemCount == arrayLength){
//do your thing here
}
rough idea. I don't have my IDE up to proof this, but basically you can set a counter to = the length of your known array, then check each value in the array to see if it contains a match..if it does, increment another counter. At the end, test your counter to see if it matches the length of your array, so in your example, if itemCount= 3, then all values matched. if it was 2, then one would be missing and your method wouldn't execute.