正则表达式匹配有效域名,如果它出现在字符串的开头。

huangapple go评论80阅读模式
英文:

Regex to match valid domain if it comes in beginning of a string

问题

我正在尝试使用正则表达式来匹配以下条件:

  1. 字符串以http或https开头
  2. 字符串以两个特定域名结尾(abc.com或xyz.com)
  3. 在abc.com或xyz.com之后可以是任何内容

我为此编写了以下正则表达式:

http
展开收缩
?:\/\/(.*).(abc|xyz).com\/(.*)

但在以下情况下它会失败,因为不应该与正则表达式匹配:

http://www.attacker.com/https://events.abc.com/#/en/navigator/init/meetings

非常感谢任何帮助。

英文:

I am trying to match the below criteria with Regex:

  1. String starts with http or https
  2. It ends with two particular domains (abc.com or xyz.com)
  3. There can be anything after abc.com or xyz.com

I wrote below regex for the same:

http
展开收缩
?:\/\/(.*).(abc|xyz).com\/(.*)

but it fails in below scenario as it shouldn't be matched with the Regex.

http://www.attacker.com/https://events.abc.com/#/en/navigator/init/meetings

Any help much appreciated

答案1

得分: 2

只返回翻译好的部分:

你可以使用以下正则表达式:

^https?:\/\/([^\/]*\.)?(abc|xyz)\.com\/.*

正则表达式演示

你需要检查在abc|xyz.com之前除了/之外的字符。

详细信息

^https?:\/\/:字符串开头的http://https://

([^\/]*\.)?:FQDN之前的任何字符(除了/),后跟一个点,这部分是可选的(?),例如//abc.com

(abc|xyz)\.com:匹配FQDN

\/.*:匹配/和之后的任何内容

英文:

You may use

^https?:\/\/([^\/]*\.)?(abc|xyz)\.com\/.*

Regex Demo

You have to check for characters except / before abc|xyz.com

Details

^https?:\/\/: http:// or https:// at the beginning of the string

([^\/]*\.)?: any character except / before FQDN followed by dot, it's optional (?) for cases like //abc.com

(abc|xyz)\.com: match FQDN

\/.*: match / and anything that comes after

答案2

得分: 1

https?:\\/\\/.*\\.(abc|xyz)\\.com\\/.*

我也从你的正则表达式中删除了一些不必要的部分:

  1. 你不需要将单个字母放在字符类中(
    展开收缩
  2. (.*) 不必要在括号中,但可能值得添加一个 ?,使其变成 .*? 以避免 * 的贪婪性。
英文:

You should escape the literals dots (.):
https?:\/\/.*\.(abc|xyz)\.com\/.*
See a demo here.

Of course, if you want to put that in a Java string literal, it's got to be
https?:\\/\\/.*\\.(abc|xyz)\\.com\\/.*

I also removed some unnecessary things from your regex:

  1. You don't need to put single letters in a character class (
    展开收缩
    )
  2. (.*) doesn't have to be in brackets, but it might be worth it to append a ? to it, so it becomes .*? to avoid greediness of *

huangapple
  • 本文由 发表于 2020年8月5日 03:43:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63254043.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定