I have this regular expression to validate the URL: ^[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$^. This regular expression works smoothly but I want to add a limit the amount of W’s in the beginning of the URL.
If the user tries to save the URL with under 3 W’s (for example ww), the regular expression will deny the save. The same result will also happens if the user tries to save the URL with more than 3 W’s (for example wwww).
How can I solve this problem?
Thanks in advance.
This sort of filtering is not a good fit for regular expressions, I think.
The problem is that the rules for what should be a “match” are actually pretty complicated. Essentially the rules are this:
Match something if it has :
wcharacters followed by a dot ORwcharacters, but the number of characters is not equal to three (plus the dot)The unless all of those characters are w characters… part is the tricky part. Regex isn’t really well suited to this task.
For “historical” purposes:
Use
{n}to repeat part of the expression n times.Use
?to make part of the expression optional.The parentheses are a grouping operator. The “w times three” and dot are moved inside the group, and the group is made optional with the
?operator.I also escaped the last forward slash with a backslash in these examples, since regular expressions are often delimited with
/characters. You can remove it if you don’t need it.