如何在不使用负后视的情况下将所有字符串与不以定义字符开头的特定 REGEX 模式匹配

How to match all strings with a specific REGEX pattern that do not start with a defined character without using a negative lookbehind

我目前有一个用例,我想匹配文本中的所有 http://https:// 字符串,但前提是它们不以 " 或 [=14 开头=] 使用 JavaScript。 如果它们以另一个字符开头,例如空格,我仍然只想匹配没有前面字符的 http://https://

我当前的正则表达式使用负向后视,但我刚刚意识到这在 Safari 中不受支持:

/(?<!["'])(https?:\/\/)/gm

那么,使用否定后视来匹配文本中的以下字符串的替代方法是什么:

你应该使用这个正则表达式:/^[a-z]+:\/\//gm

示例

const pattern = /^[a-z]+:\/\//gm
const string = `http://
https://
xhttp://
"http://
'https://`
console.log(string.match(pattern));
// Output: [ 'http://', 'https://', 'xhttp://' ]

这里不需要lookbebind,使用字符class和组:

const vars = ['http://', 'https://', 'xhttps://', '"https://']
const re = /(?:[^'"]|^)(https?:\/\/)/
vars.forEach(x => 
   console.log(x, '- >', (x.match(re) || ['',''])[1])
)

Regex:

(?:[^'"]|^)(https?:\/\/)

解释

--------------------------------------------------------------------------------
  (?:                      group, but do not capture:
--------------------------------------------------------------------------------
    [^'"]                    any character except: ''', '"'
--------------------------------------------------------------------------------
   |                        OR
--------------------------------------------------------------------------------
    ^                        the beginning of the string
--------------------------------------------------------------------------------
  )                        end of grouping
--------------------------------------------------------------------------------
  (                        group and capture to :
--------------------------------------------------------------------------------
    http                     'http'
--------------------------------------------------------------------------------
    s?                       's' (optional (matching the most amount
                             possible))
--------------------------------------------------------------------------------
    :                        ':'
--------------------------------------------------------------------------------
    \/                       '/'
--------------------------------------------------------------------------------
    \/                       '/'
--------------------------------------------------------------------------------
  )                        end of