Javascript 正则表达式 "Invalid group"?

Javascript regex "Invalid group"?

我正在尝试让 javascript 用户名验证正则表达式

' ^(?=.{4,16}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$
'  └─────┬────┘└───┬──┘└─────┬─────┘└─────┬─────┘ └───┬───┘
'        │         │         │            │           no _ or . at the end
'        │         │         │            │
'        │         │         │            allowed characters
'        │         │         │
'        │         │         no __ or _. or ._ or .. inside
'        │         │
'        │         no _ or . at the beginning
'        │
'        username is 4-16 characters long

当我在 Titanium Appcelerator 上使用它时出现此错误

[ERROR] :  Error generating AST for "***register.js"
[ERROR] :  Invalid regular expression: /^(?=.{4,16}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/: Invalid group
[ERROR] :  Alloy compiler failed

我的代码:

var regex = /^(?=.{4,16}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/;

        if ( !regex.test(e.value)) 
         {
            inputs.Username.borderColor = 'red';
            inputs.Username.backgroundColor = '#edcaca';
            return false;
         }

any idea why its giving error invalid group ?

JavaScript 的正则表达式引擎不支持 lookbehind: (?<![_.]).

这可能对你有用:

/^(?=.{4,16}$)(?![_.])(?!.*[_.]{2})[a-z0-9._]+[a-z0-9]$/i

或者避免大部分前瞻:

/^(?!.*[_.]{2})[a-z0-9][a-z0-9._]{2,14}[a-z0-9]$/i

Try it online

问题是 JavaScript 不支持回顾(正面 (?<=...) 和负面 (?<!...))。