0

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

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

it Works :) !Pattern.compile("[()<>/;\*%$].*").matcher(res).find()
Beware with you \* here: it will match a literal star. If this is what you want, fine. If you want to match both a backslash and a star, you need to match against "[()<>/;\\\\*%$]".
2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.