[英]RegEx for matching specific URLs
我正在尝试在python中编写一个正则表达式,它将匹配一个URL(例如https://www.foo.com/ )或一个以“sc-domain:”开头但没有https的域名或路径。
例如,以下条目应该通过
https://www.foo.com/
https://www.foo.com/bar/
sc-domain:www.foo.com
但是,以下条目应该失败
htps://www.foo.com/
https:/www.foo.com/bar/
sc-domain:www.foo.com/
sc-domain:www.foo.com/bar
scdomain:www.foo.com
现在我正在使用以下内容:
^(https://*/|sc-domain:^[^/]*$)
这几乎可以工作,但仍然允许像sc-domain:www.foo.com/这样的提交。 具体来说, ^[^/]*$
部分不会捕获'/'不应该传递。
你可以使用这个正则表达式,
^(?:https?://www\.foo\.com(?:/\S*)*|sc-domain:www\.foo\.com)$
说明:
^
- 开始行 (?:
- 开始非团体交替 https?://www\\.foo\\.com(?:/\\S*)*
- 这匹配以http://或https://开头的网址,后跟www.foo.com,后面还可选择路径运用 |
- 以sc-domain开头的字符串的替换: sc-domain:www\\.foo\\.com
- 此部分开始与sc-domain匹配:后跟www.foo.com,并且不允许任何文件路径 )$
- 关闭非分组模式和字符串结尾。 此外,有点不确定你是否想要允许任何随机域,但如果你想允许,你可以使用这个正则表达式,
^(?:https?://(?:\w+\.)+\w+(?:/\S*)*|sc-domain:(?:\w+\.)+\w+)$
此表达式也可以使用两个可以根据需要修改的简单捕获组来实现:
^((http|https)(:\/\/www.foo.com)(\/.*))|(sc-domain:www.foo.com)$
我还添加了http,你可以删除它,如果它可能是不受欢迎的。
const regex = /^(((http|https)(:\\/\\/www.foo.com)(\\/.*))|(sc-domain:www.foo.com))$/gm; const str = `https://www.foo.com/ https://www.foo.com/bar/ sc-domain:www.foo.com http://www.foo.com/ http://www.foo.com/bar/ `; const subst = `$1`; // The substituted value will be contained in the result variable const result = str.replace(regex, subst); console.log('Substitution result: ', result);
您只需使用Python进行测试并添加所需的捕获组:
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"^((http|https)(:\/\/www.foo.com)(\/.*))|(sc-domain:www.foo.com)$"
test_str = ("https://www.foo.com/\n"
"https://www.foo.com/bar/\n"
"sc-domain:www.foo.com\n"
"http://www.foo.com/\n"
"http://www.foo.com/bar/\n\n"
"htps://www.foo.com/\n"
"https:/www.foo.com/bar/\n"
"sc-domain:www.foo.com/\n"
"sc-domain:www.foo.com/bar\n"
"scdomain:www.foo.com")
subst = "$1 $2"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
根据Pushpesh的建议,您可以使用环视并将其简化为:
^((https?)(:\/\/www.foo.com)(\/.*))|(sc-domain:www.foo.com)$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.