Reputation: 4427
I need to scroll a List and removing all strings that contains some special char. Using RegEx I'm able to remove all string that start with these special chars but, how can I find if this special char is in the middle of the string?
For instance:
Pattern.matches("[()<>/;\\*%$].*", "(123)")
returns true and I can remove this string
but it doesn't works with this kind of string: 12(3).
Is it correct to use \* to find the occurrence of "*" char into the string?
Thanks for the help! Andrea
Upvotes: 0
Views: 3724
Reputation: 41757
Try the following:
!Pattern.matches("^[^()<>/;\\*%$]*$", "(123)")
This uses a negated character class to ensure that all the characters in the string are not any of the characters in the class.
You then obviously negate the expression since you are testing for a string that does not match.
Is it correct to use \* to find the occurrence of "*" char into the string?
Yes.
Upvotes: 2
Reputation: 121710
You are yet another victim of Java's ill-named .matches()
which tries and match the whole input and contradicts the very definition of regex matching.
What you want is matching one character among ()<>/;\\*%$
. With Java, you need to create a Pattern
, a Matcher
from this Pattern
and use .find()
on this matcher:
final Pattern p = pattern.compile("[()<>/;\\*%$]");
final Matcher m = p.matcher(yourinput);
if (m.find()) // match, proceed
Upvotes: 5
Reputation:
Pattern.matches()
tries to match the whole input. So since your regex says that the input has to start with a "special" char, 12(3)
doesn't match.
Upvotes: 0