简体   繁体   中英

JS Regex to allow only numbers, semicolon and hyphen

I am building an application which should accept strings only with the following formats:

  1. 12345 (only a number)
  2. 12345;23456 (two or more numbers separated by ;)
  3. 12345-12367 (a range of numbers separated by a -)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM