ruda
ruda

Reputation: 181

Regular expression conditional with JQuery

I need a regular expression to match sentences like:

1: 99.99.99

2: 99.99.99,99

The comma is optional and if given it must have 1 or 2 digits after it. I have this regex which matches the first sentence, but doesn't matches the second:

^(?:[0-9]{1,2}\.){2}[0-9]{1,2}$

Upvotes: 0

Views: 480

Answers (3)

hwnd
hwnd

Reputation: 70732

You can use the following.

^(?:[0-9]{1,2}\.){2}[0-9]{1,2}(?:,[0-9]{1,2})?$

See Live demo

Regular expression:

^               the beginning of the string
(?:             group, but do not capture (2 times):
 [0-9]{1,2}     any character of: '0' to '9' (between 1 and 2 times)
 \.             '.'
){2}            end of grouping
 [0-9]{1,2}     any character of: '0' to '9' (between 1 and 2 times)
 (?:            group, but do not capture (optional)
   ,            ','
   [0-9]{1,2}   any character of: '0' to '9' (between 1 and 2 times)
 )?             end of grouping
$               before an optional \n, and the end of the string

Upvotes: 1

Praveen
Praveen

Reputation: 56509

Try this

^(?:[0-9]{1,2}\.){2}[0-9]{1,2}(,[0-9]{1,2})?$

Better exp:

(,[0-9]{1,2})?

[0-9]{1,2} any numbers upto limit 2
(,?[0-9]{1,2})? this entire group upto limit 1

Upvotes: 1

M21B8
M21B8

Reputation: 1887

try this:

^(?:[0-9]{1,2}\.){2}[0-9]{1,2}(,[0-9]{1,2})?$

(untested, written off the top of my head)

edit: had a random $ in the middle

Upvotes: 1

Related Questions