正则表达式模式/(http:\ / \ / | https:\ / \ /)[^ w {3}] /不起作用

时间:2018-12-28 09:54:43

标签: javascript regex

我需要将不带'www'的http://或https://替换为'www'。我正在使用以下模式,

/(http:\/\/|https:\/\/)[^w{3}]/

但不起作用。 这是我要搜索的文字

  

网址为http://google.com http://www.google.com https://google.com   https://google.com

https://regex101.com/r/JhMN6t/1

谢谢。

5 个答案:

答案 0 :(得分:2)

[^w{3}]匹配不与w{3}相同的单个字符。

您想使用否定的前瞻断言:

/https?:\/\/(?!www)/

// or maybe even
/https?:\/\/(?!www\.)/

(?!www)的意思是“后面没有 www ”。

答案 1 :(得分:1)

您可以使用以下正则表达式:(http:\/\/|https:\/\/)(?!www)

(?!是一个否定的前瞻性,它确保不遵循内部指定的内容,而不会消耗字符

https://regex101.com/r/6TEv2r/1

答案 2 :(得分:1)

您使用的否定字符类[^w{3}]w{}3中的一个都不匹配。

您可以使用否定的lookahead来断定右边的不是www。并替换为第一个捕获组,后跟www和一个点。

请注意,可以使用问号将替换选项缩短为https?

匹配

const regex = /(https?:\/\/)(?!www\.)

替换为:

$1www.

const regex = /(https?:\/\/)(?!www\.)/g;
const str = `the url is http://google.com http://www.google.com https://google.com https://google.com`;
const subst = `$1www.`;

const result = str.replace(regex, subst);

console.log(result);

答案 3 :(得分:1)

尝试此正则表达式:

(https?:\/\/(?!www))

将匹配项替换为:

$1www.

Click for Demo

说明:

  • https?:\/\/-匹配http://https://
  • (?!www)-仅在当前位置后没有www
  • 时匹配
  • ()-用括号括起来可以将一个组中的整个比赛捕获

将整个比赛替换为第1组,后跟www.

答案 4 :(得分:0)

您也可以尝试

/^(http:\/\/|https:\/\/|http:\/\/|https:\/\/)/gm

相关问题