[英]URL regexp validation: deny if there isn't 3 W's in URL
I have this regular expression to validate the URL: ^[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$^
.我有这个正则表达式来验证 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.这个正则表达式工作顺利,但我想在 URL 的开头添加一个限制 W 的数量。
If the user tries to save the URL with under 3 W's (for example ww), the regular expression will deny the save.如果用户尝试保存小于 3 W 的 URL(例如 ww),则正则表达式将拒绝保存。 The same result will also happens if the user tries to save the URL with more than 3 W's (for example wwww).如果用户尝试保存具有超过 3 个 W 的 URL(例如 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 :如果它有匹配的东西:
w
characters followed by a dot OR正好三个w
字符后跟一个点ORw
characters, but the number of characters is not equal to three (plus the dot)除非所有这些字符都是w
字符,但字符数不等于三个(加上点)The unless all of those characters are w characters... part is the tricky part.除非所有这些字符都是 w 字符...部分是棘手的部分。 Regex isn't really well suited to this task.正则表达式不太适合这项任务。
For "historical" purposes:出于“历史”目的:
Use {n}
to repeat part of the expression n times.使用{n}
将表达式的一部分重复n次。
^w{3}\.[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?$
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 ?
“w乘以三”和点在组内移动,并且组是可选的?
operator.操作员。
^Guess what? this doesn't work.$
^I tried to delete the answer but I can't until you unaccept it.$
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.如果你不需要它,你可以删除它。
This regex will apply to all test cases此正则表达式将适用于所有测试用例
"^(https?:\\/\\/)?www{1}\." +
"((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" +
"((\\d{1,3}\\.){3}\\d{1,3}))" +
"(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*"`enter code here`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.