bradley
bradley

Reputation: 776

Regex validation for comma separated string

I need to validate and input string client side.

Here is an example of the string:

1:30-1:34, 1:20-1:22, 1:30-1:37, 

It's basically time codes for a video.

Can this be done with regex?

Banging my head against the wall...

Upvotes: 1

Views: 3211

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336088

^(?:\b\d+:\d+-\d+:\d+\b(?:, )?)+$

would probably work; at least it matches your example. But you might need to add a few edge cases to make the rules for matching/not matching clearer.

^        # Start of string
(?:      # Try to match...
 \b      # start of a "word" (in this case, number)
 \d+     # one or more digits
 :       # a :
 \d+     # one or more digits
 -       # a dash
 \d+     # one or more digits
 :       # a :
 \d+     # one or more digits
 \b      # end of a "word"
 (?:, )? # optional comma and space
)+       # repeat one or more times
$        # until the end of the string

Upvotes: 2

KJ Saxena
KJ Saxena

Reputation: 21828

The following is a simple representation. I have assumed that the string has the exact same form as you have shown. This may be a good starting point for you. I'll improve the regex if you provide more specific requirements.

([0-9]+:[0-9]{1,2}-[0-9]+:[0-9]{1,2},\w*)+

Explanation (inspired from Tim above)

[0-9]+   #One ore more digits
:      # A colon
[0-9]{1,2}  #A single digit or a pair of digits
-       #A dash
,       #A comma
\w*      #Optional whitespace

Upvotes: 0

Related Questions