英文:
Regex to match valid domain if it comes in beginning of a string
问题
我正在尝试使用正则表达式来匹配以下条件:
- 字符串以http或https开头
- 字符串以两个特定域名结尾(abc.com或xyz.com)
- 在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:
- String starts with http or https
- It ends with two particular domains (abc.com or xyz.com)
- 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\/.*
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\\/.*
我也从你的正则表达式中删除了一些不必要的部分:
- 你不需要将单个字母放在字符类中(
)展开收缩 (.*)不必要在括号中,但可能值得添加一个?,使其变成.*?以避免*的贪婪性。
英文:
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:
- You don't need to put single letters in a character class (
)展开收缩 (.*)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*
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论