Pradeep Rajkumar
Pradeep Rajkumar

Reputation: 937

Regular expression for optional character in between the numerals

I need to validate a string that contains underscore(_) in between the numbers. Underscore character is an optional. Only condition is, it should be between the numbers.

Valid     => 123
Valid     => 1_23
Valid     => 123_4567_89_312_575

Not valid => 123_
Not valid => _123
Not valid => 123__12   (Two consecutive underscore characters)
Not valid => _         (Number is mandatory)
Not valid => abc       (only numbers and _ should be present)

I have tried this regular expression

([0-9]+_*[0-9]+)*

It failed. Any idea why ?

PS: Going to implement this in swift language. Core logic: Underscore character is used like a separator for numbers.

Upvotes: 3

Views: 8990

Answers (3)

beingmanish
beingmanish

Reputation: 1110

Simple it should be either:

^[0-9]+(_[0-9]+)*$ or

^\d+(_\d+)*$ ,

both of which means start with any number(<number>) then have any(zero or more) number of combinations of pattern(_<number>) underscore and number.

OR vice-versa,

([0-9]+_)*[0-9]+ or

(\d+_)*\d+ ,

both of which means start with any(zero or more) number of combinations of pattern(<number>_) number and underscore; and then have any number(<number>).

Upvotes: 3

Jogendar Choudhary
Jogendar Choudhary

Reputation: 3494

You may use this expression:

^\d+(_\d+)*$

enter image description here

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

Your ([0-9]+_*[0-9]+)* pattern matches 0+ repetitions of 1+ digits, 0+ underscores and then 1+ digits. So, it can match 12, 3_______4, 2345, and an empty string. Depending on what method you are using it in, it may match partial, or the whole string.

You may use

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

See the regex demo

If you use the pattern inside NSPredicate with MATCHES, the ^ and $ anchors are not necessary as in that case the whole string should match the pattern.

Details

  • ^ - start of string
  • [0-9]+ - 1+ digits
  • (?: - start of a non-capturing grouping
    • _ - an underscore
    • [0-9]+ - 1+ digits
  • )* - repeats the pattern sequence 0 or more times
  • $ - end of string.

Upvotes: 3

Related Questions