3

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.

Pradeep Rajkumar
  • 919
  • 2
  • 12
  • 27

3 Answers3

3

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.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
3

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>).

Community
  • 1
  • 1
beingmanish
  • 1,040
  • 8
  • 21
2

You may use this expression:

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

enter image description here

Jogendar Choudhary
  • 3,476
  • 1
  • 12
  • 26
  • oh u very smartly edited and matched with mine regex, finally ! – beingmanish May 12 '18 at 19:38
  • Please check, this is not yours – Jogendar Choudhary May 12 '18 at 19:40
  • 1
    oh man you just deleted your 1st answer and posted one which is another form of mine regex, which also says start with number and then have any combination of (_)*. Anyway, whatever it is not sure what you want to achieve by again and again deleting and changing your answers, it's good that finally you realized that your initial answer("^[0-9]+(_*[0-9]+)*$";) was incorrect. – beingmanish May 12 '18 at 19:45
  • Yes man, That time I didn't read question bottom line "PS: Two consecutive underscore character is invalid. Going to implement this in swift language." that's why. Thank you – Jogendar Choudhary May 12 '18 at 19:46