-
August 9th, 2012, 11:31 AM
#1
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
-
August 9th, 2012, 12:11 PM
#2
Re: Use string contains for multiple checks
You could use:
Code:
if ( value.contains("?") || value.contains("!") ) {...}
Or you could use a regex Matcher.
-
August 9th, 2012, 12:43 PM
#3
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
-
August 10th, 2012, 07:18 AM
#4
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.
Last edited by AlbertGM; August 10th, 2012 at 07:27 AM.
Please, correct me. I'm just learning.... and sorry for my english :-)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|