Reputation: 937
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
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
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