Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if only chosen characters are in a string?

What's the best and easiest way to check if a string only contains the following characters:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_

I want like an example like this pseudo-code:

//If String contains other characters
else
//if string contains only those letters

Please and thanks :)

like image 498
Joseph Avatar asked Dec 13 '10 22:12

Joseph


People also ask

How do I check if a string contains only certain characters?

Use the re. match() method to check if a string contains only certain characters. The re. match method will return a match object if the string only contains the specified characters, otherwise None is returned.

How do you check if a string is only letters?

To check if String contains only alphabets in Java, call matches() method on the string object and pass the regular expression "[a-zA-Z]+" that matches only if the characters in the given string is alphabets (uppercase or lowercase).

How do you check if a string contains a certain character in Java?

The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not.

How do I check if a string contains only one word?

You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false . Also note that string positions start at 0, and not 1.


2 Answers

if (string.matches("^[a-zA-Z0-9_]+$")) {
  // contains only listed chars
} else {
  // contains other chars
}
like image 92
Pablo Lalloni Avatar answered Oct 11 '22 17:10

Pablo Lalloni


For that particular class of String use the regular expression "\w+".

Pattern p = Pattern.compile("\\w+");
Matcher m = Pattern.matcher(str);

if(m.matches()) {} 
else {};

Note that I use the Pattern object to compile the regex once so that it never has to be compiled again which may be nice if you are doing this check in a-lot or in a loop. As per the java docs...

If a pattern is to be used multiple times, compiling it once and reusing it will be more efficient than invoking this method each time.

like image 37
Andrew White Avatar answered Oct 11 '22 19:10

Andrew White