繁体   English   中英

如何为这个表达式写一个正则表达式?

[英]how to write a regex for this expression?

url1 = http://xyz.com/abc
url2 = http://xyz.com//abc

我想编写一个验证url1url2regex

为什么不直接使用urlparse呢?

你可以使用这个正则表达式:

\w{4}\:\/{2}\w+\.\w+\/{1,2}\w+

说明:

\w{4} match any word character [a-zA-Z0-9_]
    Quantifier: Exactly 4 times
\: matches the character : literally
\/{2} matches the character / literally
    Quantifier: Exactly 2 times
\w+ match any word character [a-zA-Z0-9_]
    Quantifier: Between one and unlimited times, as many times as possible, giving back as needed
\. matches the character . literally
\w+ match any word character [a-zA-Z0-9_]
    Quantifier: Between one and unlimited times, as many times as possible, giving back as needed
\/{1,2} matches the character / literally
    Quantifier: Between 1 and 2 times, as many times as possible, giving back as needed 
\w+ match any word character [a-zA-Z0-9_]
    Quantifier: Between one and unlimited times, as many times as possible, giving back as needed

希望这可以帮助。

http://\w+\.\w+//?\w+

答案取决于您是否要解析一般的网址,或者您是否只是想知道如何处理可选的斜杠。

在第一种情况下,我同意Amber你应该使用urlparse。

在第二种情况下,使用? 在表达式中的斜杠之后:

http://xyz.com//?abc

一个? 在正则表达式中表示前一个元素是可选的(即可能出现零次或一次)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM