这个匹配 URL 的正则表达式有什么问题?
我在使用 C 中的 regex.h 库设置正则表达式来匹配 URL 时遇到了一些困难。我有一个有效的 IP 正则表达式,我希望将其转换为匹配简单的字符串,例如 www.alphanumerictext12 .com|edu|org
。我的正则表达式定义本身的语法有问题。
下面是有效的 IPREGEX 代码和我尝试的 URL 正则表达式。
#define IPEXPR "([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})"
#define URLEXPR "(www)\\.((?:[a-z][a-z]*[0-9]+[a-z0-9]*))\\.(com|edu|org)"
regex_t regex;
if(regcomp(®ex, IPEXPR, REG_EXTENDED) != 0)
return 0;
if(regexec(®ex, inputURL, 0, NULL, 0) != 0)
return 0;
I'm having a bit of difficulty setting up a regex to match a URL using the regex.h library in C. I have a working IP regex that I was hoping to convert to match a simple string such as www.alphanumerictext12.com|edu|org
. Something is wrong with my syntax in the regex definition itself.
Below is the working IPREGEX code and my attempted URL regex.
#define IPEXPR "([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})"
#define URLEXPR "(www)\\.((?:[a-z][a-z]*[0-9]+[a-z0-9]*))\\.(com|edu|org)"
regex_t regex;
if(regcomp(®ex, IPEXPR, REG_EXTENDED) != 0)
return 0;
if(regexec(®ex, inputURL, 0, NULL, 0) != 0)
return 0;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试:
我删除了
[0-9]+
并将[az][az]*
替换为[az]+
。Try:
I removed the
[0-9]+
and replaced[a-z][a-z]*
with[a-z]+
.问题出在
(?: )
中,您只需要(www)\\.([az][az]*[0-9]+[a-z0-9]* )\\.(com|edu|org)
。顺便说一句,你的内心表达是:“至少一个字母字符,然后至少一个数字字符,然后是任何字母数字字符”。是你的意思吗?如果是这样,您可以将其缩短一点:
[az]+[0-9]+[a-z0-9]*
。The problem is in
(?: )
, You need just(www)\\.([a-z][a-z]*[0-9]+[a-z0-9]*)\\.(com|edu|org)
.Btw, your inner expression says: "at least one alpha character, then at least one numeric character, then any alphanumeric characters". Is it what you mean? If so, you can make it a little bit shorter:
[a-z]+[0-9]+[a-z0-9]*
.您可能应该使用
inet_pton()
这是一个标准 POSIX 函数(替换inet_aton()
)并处理 IPv4 和 IPv6 地址格式。You probably should be using
inet_pton()
which is a standard POSIX function (replacinginet_aton()
) and handles both IPv4 and IPv6 address formats.来自编码恐怖:
我的意思是:您确定正则表达式是解决您的问题的最佳方法吗?也许你可以用一些更轻量级的方法来测试该字符串是否是一个URL?
编辑
我的计算机上的以下程序,输出重定向到
/dev/null
,打印(到stderr
)程序列表:< /强>
From Coding Horror:
What I mean is: are you sure a regular expression is the best way to solve your problem? Maybe you can test whether the string is a URL with some more lightweigth method?
Edit
The following program on my computer, with output redirected to
/dev/null
, prints (tostderr
)Program Listing: