我的 REGEX 是否有替代方案可以在 Safari 中运行,用于正向和负向前瞻和负向后视?

Is there an alternative for positive & negative lookahead and negative lookbehind for my REGEX that would work in Safari?

我有一个正则表达式来检查用户名的有效性,如下所示:

/^(?=.{5,30}$)(?![_.-])(?!.*[_.-]{2})[a-zA-Z0-9._-]+(?<![_.-])$/

基本上,我的用户名有以下限制:

此 REGEX 在 Chrome 中完美运行,但众所周知,Safari 不支持 REGEX 中的 lookbehind。但是,我不确定他们是否支持前瞻。

我的问题是,有没有办法将这个 REGEX 转换成 Safari 可以理解的东西?

提前致谢!

您可以将正则表达式改写为:

/^(?=.{5,30}$)(?![_.-])(?!.*[_.-]{2})[a-zA-Z0-9._-]*[a-zA-Z0-9]$/
                                                     ^^^ change is here

我使用的逻辑依赖于在模式末尾进行否定回顾的唯一目的是断言最终字符是 不是 点、下划线或连字符。我们可以改用字符 class 来处理这个问题。请注意,作为副作用,紧邻的前一个字符 class 变为零次或多次,因为现在最后一个字符将始终满足一个或多个要求。

您可以使用以下正则表达式。

^(?=.{5,30}$)[a-z0-9]+(?:[._-][a-z0-9]+)*[a-z0-9]*$

设置了不区分大小写的标志。

正则表达式引擎执行以下操作。

^             match beginning of string
(?=.{5,30}$)  assert string contains 5-30 chars 
[a-z0-9]+     match 1+ alphanumeric chars
(?:           begin non-capture group
  [._-]       match one char in char class
  [a-z0-9]+   match 1+ chars in char class
)*            end non-cap group and execute 0+ times
[a-z0-9]*     match 0+ chars in char class
$             # match end of line