简体   繁体   中英

Javascript regex to make sure that string matches format x:y

I am trying to parse a string which has two numbers, both can be between 1 and 3 digits, and will have a colon in between. Here are some examples:

"1:1"
"1:12"
"12:1"
"123:12"

Also, the given string may also be invalid, and I need to detect if it is. My attempts so far to make sure the string is valid have looked like this: .match(/[1-9]\\:[1-9]/); . But then I noticed that this wont work if a string such as this is inputted: "characters12:4characters" . How would I go about validating the string to make sure it is in the format x:y?

Any help would be deeply appreciated.

Edit: numbers which contain 0 at the beginning is valid, but may not be given.

You may use

/^\d{1,3}:\d{1,3}$/

See the regex demo

Details

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