Reputation: 43
I need to validate a string entered by user. The string should allow numbers or ranges, separated by comma. The numbers must be between 1 and 64.
Sample: 1,8,7-9,10-12,20-45
A space is allowed before and after a comma or '-'.
Upvotes: 2
Views: 2743
Reputation: 174766
Here you go,
^(?:6[0-4]|[1-5]\d|[1-9])(?: *- *(?:6[0-4]|[1-5]\d|[1-9]))?(?: *, *(?:6[0-4]|[1-5]\d|[1-9])(?: *- *(?:6[0-4]|[1-5]\d|[1-9]))?)*$
I used <space>*
instead of \s*
because \s
matches newline characters also. Use \s
instead of a space, if you have no problem about newline character. Use \s?
instead of <space>*
, if you want to allow an optional space not zero or more spaces.
Upvotes: 2
Reputation: 5684
This looks like it's going to be gross. I don't think there's a simple answer because regex matches strings, not numbers. as it turns out, a number between 0 and 64 looks something like this
[1-6]?[0-9]
some maybe with a range incorporated (but not spaces or commas)
[1-6]?[0-9](\-[1-6]?[0-9])?
EDIT
Here I manually entered spaces and commas with a "?" directly after (appears once or not at all), if you'll allow multiple space, change the relevant "?" to "*" I can't 100% promise this will work, but constructing it piece by piece, I believe it will work.
\([1-6]?[0-9]\( ?\- ?[1-6]?[0-9]\)? ?,? ?\)+
I will try to update if I cook up something better.
EDIT2
My old pattern would match 0 if I had written in grouping correctly. Let's try this:
((([1-5]?[0-9])|(6[0-4])((\s?\-\s?([1-5]?[0-9])|(6[0-4]))?)(\s?,\s?)?)+
Happy Coding! Leave a comment if you have any questions.
Upvotes: 0
Reputation: 23064
This should match an integer between 1-64.
([1-9]|[1-5][0-9]|6[0-4])
This should accept ranges as well.
([1-9]|[1-5][0-9]|6[0-4])(-([1-9]|[1-5][0-9]|6[0-4]))?
To match one or more in a single line.
^(([1-9]|[1-5][0-9]|6[0-4])(-([1-9]|[1-5][0-9]|6[0-4]))?\s*($|,\s*))+$
Upvotes: 2