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

正则表达式匹配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 R语言爬虫的时候元素和园代码不一样怎么解决呀
  • ¥15 VS2022多项目启动有问题
  • ¥15 SQL删除添加数据后序号不连续问题。
  • ¥15 首次运行OmniEvent运行报错
  • ¥15 有没有人知道这个问题怎么解决
  • ¥15 comsol电力电缆载流量仿真
  • ¥15 webSocket可以接TCP socket接口吗
  • ¥60 mpi并行出错,CFD++计算
  • ¥15 c#:vsto,powerpoint的外接程序中换主题颜色
  • ¥15 状态机/汽车转向灯/Sateflow