duanlu1908 2018-10-04 13:48
浏览 1314
已采纳

正则表达式匹配golang中不以www开头的字符串

I have the following RegEx ^http:\/\/(?!www\.)(.*)$

Expected behavior:

http://example.com - Match
http://www.example.com - Does not match

It looks like golang does not support negative lookahead. How can I rewrite this RegEx to work on golang?

UPDATE

I'm not coding using golang, I'm using Traefik that accepts a Regex (golang flavor) as a config value, so basically I have this:

regex = "^https://(.*)$"
replacement = "https://www.$1"

What I want is to always add www. to the URL, but NOT if the URL has it already, otherwise it would become www.www.*

  • 写回答

2条回答 默认 最新

  • doukengsha9472 2018-10-04 14:02
    关注

    If you're really bent on creating a negative lookahead manually, you will need to exclude all possible w in the regexp:

    ^https?://(([^w].+|w(|[^w].*)|ww(|[^w].+)|www.+)\.)?example\.com$
    

    This regexp allows any word with a dot before example.com, unless that word is just www. It does so by allowing any word that does not start with w, or, if it starts with w it is either just that w or followed by a non-w and other stuff. If it starts with two w, then it must be either just that or followed by a non-w. If it starts with www, it must be followed by something.

    Demo

    The clarification makes this much much easier. The approach is to always (optionally) match www. and then to put that back in the replacement always:

    Search:

    ^http://(?:www\.)?(.*)\b$
    

    Replace:

    http://www.$1
    

    Demo 2

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?