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条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵