Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate numeric values which may contain dots or commas?

I need a regular expression for validation two or one numbers then , or . and again two or one numbers.

So, these are valid inputs:

11,11   11.11   1.1   1,1   
like image 623
user256034 Avatar asked Mar 28 '11 10:03

user256034


People also ask

What is the regex for comma?

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.

What is Dot in regex?

In regular expressions, the dot or period is one of the most commonly used metacharacters. Unfortunately, it is also the most commonly misused metacharacter. The dot matches a single character, without caring what that character is. The only exception are line break characters.

How do you match periods in regex?

The period (.) represents the wildcard character. Any character (except for the newline character) will be matched by a period in a regular expression; when you literally want a period in a regular expression you need to precede it with a backslash.


2 Answers

\d{1,2}[\,\.]{1}\d{1,2} 

EDIT: update to meet the new requirements (comments) ;)
EDIT: remove unnecesary qtfier as per Bryan

^[0-9]{1,2}([,.][0-9]{1,2})?$ 
like image 193
user237419 Avatar answered Oct 03 '22 04:10

user237419


In order to represent a single digit in the form of a regular expression you can use either:

[0-9] or \d

In order to specify how many times the number appears you would add

[0-9]*: the star means there are zero or more digits

[0-9]{2}: {N} means N digits

[0-9]{0,2}: {N,M} N digits to M digits

Lets say I want to represent a number between 1 and 99 I would express it as such:

[0-9]{1,2} or \d{1,2}

Or lets say we were working with binary display, displaying a byte size, we would want our digits to be between 0 and 1 and length of a byte size, 8, so we would represent it as follows:

[0-1]{8} representation of a binary byte

Then if you want to add a , or a . symbol you would use:

\, or \. or you can use [.] or [,]

You can also state a selection between possible values as such

[.,] means either a dot or a comma symbol

And you just need to concatenate the pieces together, so in the case where you want to represent a 1 or 2 digit number followed by either a comma or a period and followed by two more digits you would express it as follows:

[0-9]{1,2}[.,]\d{1,2}

Also note that regular expression strings inside C++ strings must be double-back-slashed so every \ becomes \\

like image 44
Merav Kochavi Avatar answered Oct 03 '22 03:10

Merav Kochavi