Reputation:
I have this method to check if a string contains a special character, but I don't want it to check for specific characters such as (+
or -
) how would I go about doing this?
public boolean containsSpecialCharacters(String teamName) {
Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(teamName);
boolean b = m.find();
if (b) {
return true;
}
return false;
}
Upvotes: 8
Views: 65118
Reputation: 70722
You can use the following. Simply add these characters inside of your negated character class.
Within a character class []
, you can place a hyphen (-
) as the first or last character. If you place the hyphen anywhere else you need to escape it (\-
) in order to be matched.
Pattern p = Pattern.compile("(?i)[^a-z0-9 +-]");
Regular expression:
(?i) # set flags for this block (case-insensitive)
[^a-z0-9+-] # any character except: 'a' to 'z', '0' to '9', ' ', '+', '-'
Upvotes: 1
Reputation: 98861
You can try this:
[^\w +-]
REGEX EXPLANATION
[^\w +-]
Match a single character NOT present in the list below «[^\w +-]»
A word character (letters, digits, and underscores) «\w»
The character “ ” « »
The character “+” «+»
The character “-” «-»
Upvotes: 8