Use string contains for multiple checks
Hi everyone
I wanted to know wether is possible to use the contains method to check multiple values.
For example:
If I want to know wether a string contains a "?" or "!". How would I change the syntax to accomodate both?
I am currenly using this : value.contains("?"); but I want to be able to put multiple characters check.
Thank you
Re: Use string contains for multiple checks
You could use:
Code:
if ( value.contains("?") || value.contains("!") ) {...}
Or you could use a regex Matcher.
Re: Use string contains for multiple checks
I was aware of that syntax where I can use "||" or "&&" to add multiple values but it's not neat and effective when you want to check multiple values as your repeating the same line of code again and again.
I never came accross a regex matcher, can you provide an example of how that would work with the two symbols I've mentioned?
Thank you
Re: Use string contains for multiple checks
Something like this should work:
Code:
Pattern p = Pattern.compile("[?!]");
Matcher m = p.matcher(value);
if (m.find()) {
System.out.println("value = " + value + " matches");
}
else {
System.out.println("value = " + value + " does NOT match");
}
Another solution could be:
Code:
if (value.matches(".*[?!].*")) {
System.out.println("value = " + value + " matches");
}
else {
System.out.println("value = " + value + " does NOT match");
}
Albert.