为什么此正则表达式与字符串不完全匹配?

时间:2019-08-22 02:17:26

标签: javascript regex

我正在尝试完全匹配“ http://”和“ https://”,以便可以将它们从URL中删除,尽管我遇到了一些麻烦,因为它也与URL本身内的字母匹配。 / p>

这是为什么,我该如何解决?

enter image description here

enter image description here

3 个答案:

答案 0 :(得分:0)

正则表达式[^https://$] 意思是:

  

匹配列表“ htps:/ $”中不存在的任何单个字符

答案 1 :(得分:0)

您拥有的正则表达式

 [^http://$]

匹配h,t,p,:,/,$以外的任何内容

您只需使用URL api即可获取主机名,如果您只想替换http or http,则可以使用replace

let urls = ['http://example.com/123', 'https://examples.com', 'example.com']

// to get hostname
urls.forEach(url => {
  if (/^https?:\/\//i.test(url)) {
    let parsed = new URL(url)
    console.log(parsed.hostname)
  } else {
    console.log(url)
  }
})

// to remove http or https
urls.forEach(url => {
  let replaced = url.replace(/^https?:\/\//i, '')
  console.log(replaced)
})

答案 2 :(得分:0)

正如其他人回答的那样,[^https://$]无效,因为[^]不是断言行首的捕获组,它是否定的字符类。您的正则表达式与字面上不是字母h, t, p, s, :, /之一的任何字符匹配。

[brackets]描述一个字符类,而(parenthesis)描述一个捕获组-可能是您想要的。您可以了解有关它们的更多信息in this excellent answer.

看起来有点像您在尝试使用^$符号,但这对您的特定正则表达式不是一个好主意。这将断言行首在h之前,而行尾在/之后,这意味着除非https://,否则正则表达式将不匹配。字符串中唯一的

如果您想匹配http://https://,则此正则表达式可以解决问题:(https{0,1}:\/\/)

BREAKDOWN

(https{0,1}:\/\/)


(               )    capture this as a group
 http                match "http"
     s{0,1}          match 0 or 1 "s"
           :         match ":"
            \/\/     match "//" literally

Try it here!

如果您想匹配()-之类的字符,也可以通过转义它们来实现:

\(\)\-    matches "()-" literally

祝你好运!