I am building an application which should accept strings only with the following formats:
The java script regex should allow only the above formats & shouldn't accept any other formats or symbols . Can anyone come up with a regex for this?
This is the RegExp that you need: /^\\d+((;\\d+)*|-\\d+)?$/
(;\\d+)*
will check for multiple numbers separated by ";"
-\\d+
will check for a range
Try
^[0-9]+([;-][0-9]+)?$
That should work
[0-9]+
matches 1 or more digits [;-] matches a ;
or a -
(...)?
is an optional match
^
anchors the start and $
anchors the end of the string
Assuming that the number portions you are looking for are 5 digits each time, the following should match what you want.
[0-9]{5}((;|-)[0-9]{5}){0,1}
If you need different lengths, you can update the {5} with either another fixed length or a range such as {3,5} for a string of 3 to 5 digits. If you want to be able to capture more than two numbers with the speperators listed, you can use
[0-9]{5}((;|-)[0-9]{5})*
^[0-9-;]{0,50}$
0-9 only accept numbers
-; allow only - and ;
{0,50} allow only 50 chars
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.