user1848712
user1848712

Reputation: 105

How to match all numerical characters and some single characters using regex

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

Answers (3)

StarsSky
StarsSky

Reputation: 6711

Regex:

String regex = "\\d/:$+";

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

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:

  • 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. [\\\\]

Upvotes: 1

anubhava
anubhava

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

Related Questions