Reputation: 105
How can I match all numbers along with specific characters in a String using regex? I have this so far
if (!s.matches("[0-9]+")) return false;
I don't understand much regex, but this matches all characters from 0-9 and now I need to be able to match other specific characters, for example "/", ":", "$"
Upvotes: 0
Views: 138
Reputation: 726509
You can add the other characters that you need to match to the end of the character group, like this:
if (!s.matches("[0-9/:$]+")) return false;
You need to be careful about several things:
^
is among the characters, it must not be the first one of the group-
is among the characters, it must be the last one in the group]
is among the characters, it needs to be escaped for regex and for Java, e.g. [\\]]
\
is among the characters, it needs to be escaped for regex and for Java, e.g. [\\\\]
Upvotes: 1
Reputation: 785058
You can use this regex by including those symbols in a character class
:
s.matches("[0-9$/:]+")
Read more about character class
Upvotes: 1