Reputation: 167
I am doing some match functions with the Java. I have some string like this park,reserved_parking etc.. If i search for the word park like this
if(input.trim().contains ("Park"))
dummies = dummies + " 1";
else
dummies = dummies + " 0";
It prints the values for reserved_parking also. I don't know how to find the exact match in Java. any help will be appreciated.
Upvotes: 0
Views: 108
Reputation: 1944
To find an exact match, you will need a Regular Expression, like this:
private boolean isMatching(String source, String stringToSearch){
String pattern = "\\b" + stringToSearch + "\\b";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(source);
return m.find();
}
The \b option in the regular expression means "word bonduary". So, this will match exactly "Park" if you pass that as a parameter in the stringToSearch, but it won't match "reserved_parking", returning false.
Upvotes: 0
Reputation: 863
Contains does what it says. It tests if the String you give as input, is somewhere in the String you test against. So "batteryparkhorsewidow".contains("park")
will return true
.
What you are looking for may be the equals method. This method tests for String equality. So it will only return true
if your String is "park" nothing more, nothing less.
Please mind that equals
works case sensitive. For a case insensitive equality check use equalsIgnoreCase
Upvotes: 2
Reputation: 129
It seems a case issue. You can lowercase or uppercase the string before checking it.
input.trim().toUpperCase().contains("PARK")
Or use some external library like Apache Commons Lang's containsIgnoreCase
StringUtils.containsIgnoreCase(input, "Park");
Upvotes: 0
Reputation: 26067
You might need to go for case in-sensitive search,
change both the input and matched String to Upper case/lower case and then match
.
Input - park
public static void main(String[] args) {
String input = "park";
if (input.trim().toUpperCase().contains("Park".toUpperCase()))
dummies = dummies + " 1";
else
dummies = dummies + " 0";
System.out.println(dummies);
}
Output
1
Input - reserved_parking
public static void main(String[] args) {
String input = "reserved_parking";
if (input.trim().toUpperCase().contains("Park".toUpperCase()))
dummies = dummies + " 1";
else
dummies = dummies + " 0";
System.out.println(dummies);
}
Output
1
Upvotes: 0