Calum Murray
Calum Murray

Reputation: 1192

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.

Upvotes: 43

Views: 297030

Answers (6)

Edwin Buck
Edwin Buck

Reputation: 70909

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.

Upvotes: 38

Jean
Jean

Reputation: 21595

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

Upvotes: 2

anubhava
anubhava

Reputation: 785186

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

Upvotes: 5

splash
splash

Reputation: 13327

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

Upvotes: 1

Shaded
Shaded

Reputation: 17836

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

Upvotes: 6

Anomie
Anomie

Reputation: 94804

You almost have it, you just left out 0 and forgot the quantifier.

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

Upvotes: 73

Related Questions