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

正则表达式匹配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条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料