问题
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 "/", ":", "$"
回答1:
You can use this regex by including those symbols in a character class
:
s.matches("[0-9$/:]+")
Read more about character class
回答2:
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:
- If
^
is among the characters, it must not be the first one of the group - If
-
is among the characters, it must be the last one in the group - If
]
is among the characters, it needs to be escaped for regex and for Java, e.g.[\\]]
- If
\
is among the characters, it needs to be escaped for regex and for Java, e.g.[\\\\]
回答3:
Regex:
String regex = "\\d/:$+";
来源:https://stackoverflow.com/questions/20952787/how-to-match-all-numerical-characters-and-some-single-characters-using-regex