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
^
- start of a string \\d{1,3}
- one, two or three digits ( \\d
is a shorthand character class that matches any digit (it can also be written as a [0-9]
character class) and {1,3}
is a limited quantifier that matches1 to 3 consecutive occurrences of the quantified subpattern) :
- a colon \\d{1,3}
- one, two or three digits $
- end of the string .
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.