Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the field contains hyphen character in java

Tags:

java

My Object returns me - from Log.d("FormattedDate", Object.getDOB());

if (!Object.getDOB().matches("[^-]*")) {
    txtDOB.setText(Object.getDOB());
   } else {
    txtDOB.setText("-");
}

I am checking if my Object.getDOB() matches with -, then show emptry strings, but this regExp is not working.

like image 556
theJava Avatar asked Jun 12 '13 10:06

theJava


2 Answers

java.lang.String has a String#contains() method that does this for you:

Returns true if and only if this string contains the specified sequence of char values.

if (Object.getDOB().contains("-")) {
    //code
}
like image 105
darijan Avatar answered Nov 14 '22 21:11

darijan


You could also use

if (Object.getDOB().indexOf("-") != -1) {
    //code
}

if it returns -1 then the string does not contain the char (in your case "-"). Otherwise it returns the index of the char.

like image 35
Priya Prajapati Avatar answered Nov 14 '22 22:11

Priya Prajapati