Regexp to match domain and subdomains (in Java)

后端 未结 3 567
心在旅途
心在旅途 2021-01-15 15:00

I need to verify if given URL matches my domain mask.

Example: I want to allow only domains which satisfy this \"pseudo-mask\":

https://*.domain.com
         


        
3条回答
  •  礼貌的吻别
    2021-01-15 15:28

    Try this:

    ^https?://(?:[^./@]+\.)*domain\.com(?![^/])

    [^.]+\. means one or more non-dot characters, followed by a dot; a quick and dirty way to match a domain-name component and its trailing dot. I wouldn't use that to find domain names in a larger body of text, but it's good enough for the kind of validating you're doing. Put that in a group and add the * quantifier to get a regex that matches zero or more components.

    You don't really care what comes after the domain name, but you do have to make sure you've reached the end of it; for example, you don't want to match http://domain.company.com. The final part of the regex, (?![^/]), is a negative lookahead that means if there is another character after this, and that character is not /, fail.

提交回复
热议问题