Tomáš Zato
Tomáš Zato

Reputation: 53149

Can I check string to contain character that I didn't list?

To check whether a string contains a specific character you can use the indexOf method.

"Blah blah.".indexOf(".");  //Returns number

I have a string that should not contain anything but letters and numbers. I could check for that via regular expression:

[^a-zA-Z0-9]
or just
[a-z\d]  /i

But in this particular case, regular expression is not welcome. In languages like C (or C++ for that matter), I'd instead loop the string through. As far as I know, in Java the [] operator is not an option for strings.

Is there an option that is faster than regexp?

Upvotes: 3

Views: 1245

Answers (4)

Alex
Alex

Reputation: 13941

If you're doing lots of validations in a tight inner loop and performance is a concern, one common pattern is to keep around a pre-compiled regex, e.g. as a static constant, to avoid the overhead of recompiling the same regex for each validation (as would be done in the convenience methods provided by String):

import java.util.regex.Pattern;

public class StringValidate {
  private static final Pattern VALID_STR = Pattern.compile("(?i)[a-z0-9]+");

  public static boolean isValidStr(String s) {
    return VALID_STR.matcher(s).matches();
  }

  public static void main(String[] args) {
    System.out.println(isValidStr("abc12d")); // true
    System.out.println(isValidStr("xyz "));   // false
  }
}

The advantage here is that you can easily tweak your validation rules over time by simply modifying the regex, with minimal code changes.

Upvotes: 1

Nathan Hughes
Nathan Hughes

Reputation: 96394

You could use String.indexOf:

boolean isLetterOrDigit(String s) {
    final String UPPERCASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    final String LOWERCASE_LETTERS = "abcdefghijklmnopqrstuvwxyz";
    final String NUMBERS = "1234567890";
    final String ALLOWED = UPPERCASE_LETTERS 
    + LOWERCASE_LETTERS + NUMBERS;
    for (char ch : s.toCharArray()) {
        if (ALLOWED.indexOf(ch) == -1) {
            return false;
        }
    } 
    return true;
}

Upvotes: 3

Bohemian
Bohemian

Reputation: 425043

You can use regex via the matches() method to test:

if (!str.matches("[a-zA-Z0-9]+")) {
    // str contains an unwanted char

FYI in java, regex flags are coded in the regex itself, so to implement your case insensitive example:

 if (!str.matches("(?i)[a-z0-9]+"))

Note also that \d is not equivalent to [0-9], because it includes all digit characters (eg Arabic, Chinese, etc).

Upvotes: 0

Anton
Anton

Reputation: 559

If I understand you correctly. There is a method called String.contains(CharSequence s) which can find any subsequence in a string. Hope it helps.

Upvotes: 0

Related Questions