3

I need to perform the following check:

IF myString.contains()

ANY CHARACTERS OTHER THAN

letters a-z, A-Z, "_", "-", numbers 0-9

THEN .....

whats is the correct java syntax for such a check?

2
  • You could use a regex to split the string on those characters and check whether the resulting groups are non-empty. Commented Feb 4, 2013 at 12:03
  • 1
    The typical Java programmer will probably use a suitable regex pattern match, no? Commented Feb 4, 2013 at 12:03

3 Answers 3

11

You could use a regular expression

Pattern badChar = Pattern.compile("[^A-Za-z0-9_-]");
if(badChar.matcher(myString).find()) {
  // ...
}

This pattern will match any single character apart from letters, numbers, underscore and hyphen.

Sign up to request clarification or add additional context in comments.

8 Comments

I'm not very good with regexes, so I'm curious: does the last "-" really need no escaping? Seems a bit odd to me if so since that would mean it's interpreted as a literal there whereas in "A-Z" it's interpreted as syntax.
@G.Bach yes, a hyphen between two other characters denotes a range, but at the beginning or end of a character class expression it is a literal hyphen.
this works, thanks. BTW, would it work with cyrillic characters?
@IanRoberts This means that usually hyphens require escaping, the exception being if they are at the beginning or end of a group of the regex?
@Maver1ck a cyrillic letter is not A-Z, a-z, 0-9, underscore or hyphen so if myString contains one then find would return true. If you want to allow non-Latin letters you could use "[^\p{L}0-9_-]" - \p{L} matches any character that is a "letter" according to the Unicode standard.
|
1
myString.matches("[^a-zA-Z0-9_-]*");

2 Comments

You probably want to add a * or + to that to allow for a string with more than one character.
@IanRoberts I just realized that, I was also forgetting to negate the content. Thanks
0

This Will Do it

String str1 = "abc,pqr"; Pattern pattern = Pattern.compile("^[a-zA-Z0-9._,-]+");

    Matcher matcher1 = pattern.matcher(str1);
    System.out.println(matcher1.matches());

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.