Nick Maroulis
Nick Maroulis

Reputation: 487

Create regular expression for

I am trying to create a regular expression to accept

an integer

123

or

an integer then underscore then another integer

123_45

Here is what I have

/^[0-9]+_*[0-9]*$/

how do i make _*[0-9]* (the second part) optional

Upvotes: 2

Views: 87

Answers (3)

joHN
joHN

Reputation: 1795

check this expression,

/^[0-9]+(_([0-9])+)?$/

it will not match 123_

Upvotes: 0

Jacob Tomlinson
Jacob Tomlinson

Reputation: 3773

Have you tried

/^[0-9]+(_[0-9]+)?$/

Optional syntax ()? taken from http://www.regular-expressions.info/optional.html

But as stated in the accepted answer \d can be used as shorthand for [0-9] so this could be

/^\d+(_\d+)?$/

Upvotes: 2

burning_LEGION
burning_LEGION

Reputation: 13450

use this regular expression ^\d+(_\d+)?$

Upvotes: 6

Related Questions