Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match digits, comma and semicolon?

Tags:

java

regex

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.

like image 447
Calum Murray Avatar asked Mar 16 '11 15:03

Calum Murray


People also ask

How do you match a semicolon in regex?

In Hosted Email Security (HES) match module, semicolon is used as a separator of expressions. Thus, if you use a semicolon (;) in a keyword expression, it will split the keywords into multiple parts. Semicolon is not in RegEx standard escape characters.

What is difference [] and () in regex?

This answer is not useful. Show activity on this post. [] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

Is comma a special character in regex?

In regex, there are basically two types of characters: Regular characters, or literal characters, which means that the character is what it looks like. The letter "a" is simply the letter "a". A comma "," is simply a comma and has no special meaning.

Which regex matches one or more digits?

Occurrence Indicators (or Repetition Operators): +: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.


2 Answers

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

word.matches("^[0-9,;]+$") 
like image 71
Anomie Avatar answered Sep 26 '22 16:09

Anomie


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.

like image 41
Edwin Buck Avatar answered Sep 22 '22 16:09

Edwin Buck