验证网址并匹配空字符串的正则表达式? [英] A regex that validates a web address and matches an empty string?
问题描述
当前表达式验证网址 (HTTP),如何更改它以便空字符串也匹配?
The current expression validates a web address (HTTP), how do I change it so that an empty string also matches?
(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?
推荐答案
如果您想修改表达式以匹配一个完全空的字符串或一个完整的 URL,您将需要使用锚元字符 ^ 和 $(分别匹配行的开头和结尾).
If you want to modify the expression to match either an entirely empty string or a full URL, you will need to use the anchor metacharacters ^ and $ (which match the beginning and end of a line respectively).
^(|https?:\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)$
正如直接指出的那样,您可以稍微简化一下协议的匹配,所以我也为您提供了.
As dirkgently pointed out, you can simplify your match for the protocol a little, so I've included that for you too.
不过,如果您在程序或脚本中使用此表达式,则使用语言自己的方法来检查输入是否为空可能更简单.
Though, if you are using this expression from within a program or script, it may be simpler for you to use the languages own means of checking if the input is empty.
// in no particular language...
if input.length > 0 then
if input matches <regex> then
input is a URL
else
input is invalid
else
input is empty
这篇关于验证网址并匹配空字符串的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!