I am trying to write a regular expression to do validation in javascript. My requirement is to validate numbers followed by underscore and again it should have numbers.
For example: 123456789_123456789
Length is not a constraint. It can have n
numbers, underscore and n
numbers.
Currently i tried with this [0-9]_[0-9]
. Is there any better way of doing it ?
Any suggestion is appreciated.
Thanks, Sreekanth
I am trying to write a regular expression to do validation in javascript. My requirement is to validate numbers followed by underscore and again it should have numbers.
For example: 123456789_123456789
Length is not a constraint. It can have n
numbers, underscore and n
numbers.
Currently i tried with this [0-9]_[0-9]
. Is there any better way of doing it ?
Any suggestion is appreciated.
Thanks, Sreekanth
Share Improve this question asked Nov 26, 2013 at 8:42 Srikanth SridharSrikanth Sridhar 2,4677 gold badges31 silver badges50 bronze badges3 Answers
Reset to default 4You almost got it. The correct regex would be :
^[0-9]{1,}_[0-9]{1,}$
or
^[0-9]+_[0-9]+$
The regex means: "one or more digits ([0-9]{1,}
), followed by an underscore (_
) and then again one or more digits ([0-9]{1,}
).
This matches:
12312_123123
1_1
but doesn't match:
123123_
_123123
_
123123_1231ddd
123dd_123
dd123_123
If the numbers are optional: /^\d*_\d*$/
, else: /^\d+_\d+$/
.
Examples:
/^\d+_\d+$/.test("123_"); // false
/^\d+_\d+$/.test("123_123"); // true
What You tried is [0-9]_[0-9]
i.e,
Possible Answer is [0-9]+_[0-9]+
i.e,