用于匹配特定 URL 的正则表达式

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://\S+)|(?:sc-domain:[^/\s]+))$

你可以试试这个。

查看演示。

https://regex101.com/r/xXSayK/2

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

^(?:https?://www\.foo\.com(?:/\S*)*|sc-domain:www\.foo\.com)$

解释:

  • ^ - 行首
  • (?: - non-group 交替开始
  • https?://www\.foo\.com(?:/\S*)* - 这匹配以 http:// 或 https:// 开头的 URL 后跟 www.foo.com 并进一步可选地后跟使用
  • 的路径
  • | - 以 sc-domain:
  • 开头的字符串的交替
  • sc-domain:www\.foo\.com - 此部分以 sc-domain 开始匹配:后跟 www.foo.com 并且进一步不允许任何文件路径
  • )$ - non-grouping 模式结束和字符串结尾。

Regex Demo

另外,有点不确定你是否想允许任何随机域,但如果你想允许,你可以使用这个正则表达式,

^(?:https?://(?:\w+\.)+\w+(?:/\S*)*|sc-domain:(?:\w+\.)+\w+)$

Regex Demo allowing any domain

This expression 也可以使用两个简单的捕获组来做到这一点,您可以根据需要进行修改:

^((http|https)(:\/\/www.foo.com)(\/.*))|(sc-domain:www.foo.com)$

我还添加了 http,如果不需要,可以将其删除。

JavaScript 测试

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 = ``;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

测试 Python

您可以简单地使用 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 = " "

# 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的建议,您可以使用lookaround并将其简化为:

^((https?)(:\/\/www.foo.com)(\/.*))|(sc-domain:www.foo.com)$