[java] Regex match digits, comma and semicolon?

What's a regular expression that will match a string only containing digits 0 through 9, a comma, and a semi-colon? I'm looking to use it in Java like so:

word.matches("^[1-9,;]$") //Or something like that...

I'm new to regular expressions.

This question is related to java regex

The answer is


You current regex will only match 1 character. you need either * (includes empty string) or + (at least one) to match multiple characters and numbers have a shortcut : \d (need \\ in a string).

word.matches("^[\\d,;]+$") 

The Pattern documentation is pretty good : http://download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html

Also you can try your regexps online at: http://www.regexplanet.com/simple/index.html


word.matches("^[0-9,;]+$"); you were almost there


You are 90% of the way there.

^[0-9,;]+$

Starting with the carat ^ indicates a beginning of line.

The [ indicates a character set

The 0-9 indicates characters 0 through 9, the comma , indicates comma, and the semicolon indicates a ;.

The closing ] indicates the end of the character set.

The plus + indicates that one or more of the "previous item" must be present. In this case it means that you must have one or more of the characters in the previously declared character set.

The dollar $ indicates the end of the line.


boolean foundMatch = Pattern.matches("[0-9,;]+", "131;23,87");

Try word.matches("^[0-9,;]+$");