Reputation: 55
I'm writing a regex for a software version field which has the following format :
xxx.yyy.zzz
These 3 parts can have between 1 to 3 digits each. Ex :
1.2.3
100.2.300
111.222.333
I formulated this regex for this purpose , but it's incorrect :
[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}
What should be modified to get it working correctly ?
Upvotes: 1
Views: 248
Reputation: 10665
You need to escape the dots in the regex, otherwise they count as any character.
var regex = /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/;
regex.test('1.2.3'); //true
regex.test('100.2.300'); //true
regex.test('111.222.333'); //true
If you don't escape the dots, you will be able to provide any character in the place of the dot.
var badRegex = /[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}/;
badRegex.test('1a2z3'); //true
badRegex.test('100-2#300'); //true
badRegex.test('111f2229333'); //true
Upvotes: 3
Reputation: 2557
Try this
\d{1,3}\.\d{1,3}\.\d{1,3}
or
[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}
Javascript
var re = /\d{1,3}\.\d{1,3}\.\d{1,3}/g;
or
var re = /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/g;
Upvotes: 1
Reputation: 20286
You should escape dot with \
and also you can use \d
which means digit
\d{1,3}\.\d{1,3}\.\d{1,3}
Upvotes: 2