string - Comma Separated Integer between 1-9999 Regex -
i'm struggling come regex list of integers separated comma , ranging between 1-9999.
this have far:
"(^[1-9][0-9]{3}|[1-9][0-9]{2}|[1-9][0-9]|[1-9](,[1-9][0-9]{3}|[1-9][0-9]{2}|[1-9][0-9]|[1-9])*)$"
i don't want allow spaces , should't end in comma, should allow:
1,2,9999 1 43,5
an integer netween 1 , 9999 can matched
(?:[1-9]|[1-9][0-9]{1,3})
that synonymic
[1-9][0-9]{0,3}
details:
[1-9]
- digit1-9
range|
- or[1-9][0-9]{1,3}
- integer10
till9999
.
or
[1-9]
- digit1-9
range[0-9]{0,3}
- 0 3 digits
so, list of integers separated comma can witten as:
\a(?:[1-9]|[1-9][0-9]{1,3})(?:,(?:[1-9]|[1-9][0-9]{1,3}))*\z
or shorter version
\a[1-9][0-9]{0,3}(?:,[1-9][0-9]{0,3})*\z
here regex demo
explanation:
\a
- unambiguous start of string[1-9][0-9]{0,3}
- integer regex block(?:
- beginning of non-capturing group match 0 or more sequences of:,
- comma[1-9][0-9]{0,3}
-1
till9999
integer regex block
)*
- end of non-capturing group\z
- unambiguous very end of string.
in swift or objective c string pattern, need double backslashes,
swift:
var pattern = "\\a[1-9][0-9]{0,3}(?:,[1-9][0-9]{0,3})*\\z"
objective c:
nsstring * pattern = @"\\a[1-9][0-9]{0,3}(?:,[1-9][0-9]{0,3})*\\z";
since need validate strings, need use unambiguous anchors \a
, \z
. note $
matches string if ends lf symbol, thus, advisable use end of string anchor \z
.
edit:
to prove below not believe objective-c pattern above not work, here demo:
nsstring * teststr = @"1,4,566"; nsstring * pattern = @"\\a[1-9][0-9]{0,3}(?:,[1-9][0-9]{0,3})*\\z"; nspredicate * tst = [nspredicate predicatewithformat:@"self matches %@", pattern]; if ([tst evaluatewithobject:teststr]) { nslog (@"yes"); } else { nslog (@"no"); }
result: yes
Comments
Post a Comment