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

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

本文介绍了正则表达式匹配golang中不以www开头的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下RegEx ^ http:\/\/(?! www \.)(.*)$

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

预期行为:

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

golang 似乎不支持否定超前.如何重写此RegEx以在 golang 上工作?

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

更新

我不是使用golang进行编码,而是使用 Traefik 接受正则表达式(golang风格)作为配置值,所以基本上我有这个:

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"

我想要的是始终在URL中添加 www.,但是如果该URL已经包含 NOT ,则为 NOT ,否则它将成为 www.www.*

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.*

推荐答案

如果您真的想手动创建否定的超前查询,则需要在正则表达式中排除所有可能的 w :

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$

此正则表达式允许在 example.com 之前带有点的任何单词,除非该单词只是 www .通过允许任何不以 w 开头的单词来做到这一点,或者,如果它以 w 开头,则只能是 w 或紧随其后由非 w 和其他东西组成.如果它以两个 w 开头,那么它必须是正好等于或后面跟一个非 w .如果它以 www 开头,则必须 后跟某些内容.

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.

演示

澄清使这变得容易得多.方法是始终(可选)匹配 www.,然后始终将其放回替换中:

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:

搜索:

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

替换:

http://www.$1

演示2

这篇关于正则表达式匹配golang中不以www开头的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 20:26