4

I have a variable length string, I just want to detect whether this string contains several characters. For example:

"sadsdd$sss^dee~"

I want to detect whether this string contains ANY of the following: $ ^ ~. How can I do that using Java string.matches?

"sadsdd$sss^dee~".matches("[^+$+~+]");
2
  • You would need to loop for each characters separately. Commented Jun 20, 2013 at 20:32
  • 4
    Does your string need to contain all of $ ^ ~ characters or one is enough? Commented Jun 20, 2013 at 20:35

3 Answers 3

5

Use a pattern and a matcher for that:

Pattern pattern = Pattern.compile("[$~^]");
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
   // contains special characters
} else {
   // doesn't contain special characters
}
Sign up to request clarification or add additional context in comments.

4 Comments

@BalintBako: no need to escape within a character class.
Although it is not what OP is asking it is better approach. +1
@Pshemo: Do you think OPs question is to check the existence of all 3 cahracters?
No, I mean that OP was asking about string.matches() solution.
1

If you really must use matches then try this way

myString.matches(".*[$^~].*");

matches checks if regex can completely match string so beside part you are interested with you also need to let it match parts before and after it, which .* should handle.

Comments

1

How to detect if one string contains one of several characters in another string:

If you want a fast solution:

public static void main(String[] args) {
    System.out.println(containsChars("sadsdd$sss^dee~", "$^~"));
}

public static boolean containsChars(String str, String chars) {
    for (int i = 0; i < chars.length(); i++) {
        char c = chars.charAt(i);
        for (int j = 0; j < str.length(); j++) {
            if (c == str.charAt(j)) {
                return true;
            }
        }
    }
    return false;
}

Certainly not as small or elegant as a regular expression, but it is fast.

2 Comments

This doesn't seen to be really fast because if the string doesn't contain any of the chars, it needs to make m*n iterations. Would this still perform better than matching a regex (even if the regex is pre-compiled)?
Short answer: Yes! More fastes that regex.

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.