Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match numbers followed by underscore and numbers?

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

like image 356
Srikanth Sridhar Avatar asked Oct 25 '25 06:10

Srikanth Sridhar


2 Answers

You 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
like image 164
Konstantin Yovkov Avatar answered Oct 26 '25 21:10

Konstantin Yovkov


If the numbers are optional: /^\d*_\d*$/, else: /^\d+_\d+$/.

Examples:

/^\d+_\d+$/.test("123_");    // false
/^\d+_\d+$/.test("123_123"); // true
like image 40
steffen Avatar answered Oct 26 '25 20:10

steffen