Reputation: 1195
I am not good with JavaScript Regex, so I need help checking my string for validation.
I am getting these image names separated by comma: Chrysanthemum.jpg,Desert.png,Hydrangeas.gif,Jellyfish.jpg,
Now I want to check with this regex:
What is valid:
Chrysanthemum.jpg,Desert.png,Hydrangeas.gif,Jellyfish.jpg,Koala.jpg,Lighthouse.png,
What is not valid:
1. Chrysanthemum.jpg,Desert.png,Hydrangeas.gif,
2. Chrysanthemum.jpg,Desert.png,
3. Chrysanthemum.jpg,
Validation should only succeed when the amount of comma separated values are more than 3.
Upvotes: 1
Views: 1939
Reputation: 174874
The below regex would validates for filename extensions, spaces after the comma except the last one and the comma seperated values are more than 3,
^[A-Z][a-z]+\.(?:jpg|png|gif),(?: [A-Z][a-z]+\.(?:jpg|png|gif),){3,}$
If the values are not seperated by comma and space then your regex would be,
^[A-Z][a-z]+\.(?:jpg|png|gif),(?:[A-Z][a-z]+\.(?:jpg|png|gif),){3,}$
OR
A much simpler one,
^(?:[A-Z][a-z]+\.(?:jpg|png|gif),){4,}$
Upvotes: 1
Reputation: 8110
Are you sure you need regex for that? Try this:
var str = "Chrysanthemum.jpg, Desert.png, Hydrangeas.gif, Jellyfish.jpg,";
var length = str.split(',').filter(function(item) { return item != ""; }).length;
if (length > 3) {
...
}
Upvotes: 0
Reputation: 41848
Here is a simple approach:
if (/(?:,\s*\S+){3}/.test(yourString)) {
// It matches!
} else {
// Nah, no match...
}
This checks that there are at least three commas followed by optional spaces, then non-space characters.
In the Regex Demo, you can see how this works (there is a match).
This option checks that you have at least four images.
if (/^\w+\.(?:jpg|png|gif)(?:, \w+\.(?:jpg|png|gif)){3}/.test(yourString)) {
// It matches!
} else {
// Nah, no match...
}
See the matches in the Regex Demo.
Upvotes: 1