【问题标题】:Javascript regex "Invalid group"?Javascript正则表达式“无效组”?
【发布时间】:2016-06-09 18:52:25
【问题描述】:

我正在尝试让 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;
         }

知道为什么它给出错误无效组吗?

【问题讨论】:

    标签: javascript appcelerator-titanium


    【解决方案1】:

    这可能对你有用:

    /^(?=.{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 不支持lookbehinds(正向(?&lt;=...) 和负向(?&lt;!...))。

    【讨论】:

    • 解决方案+问题解释,最佳答案,,,,谢谢:)你疯了我的一天
    • @NinjaDevelopers 很高兴它对您有所帮助:-)。通常可以像我上面所做的那样避免后视。
    【解决方案2】:

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

    【讨论】:

    • 我不理解“不支持后视”,你是说这部分吗? (?![_.])
    • (?&lt;!...) 是消极的后视,不幸的是不支持。
    猜你喜欢
    • 1970-01-01
    • 2011-05-11
    • 2022-01-25
    • 2020-09-02
    • 2013-12-02
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 2019-10-18
    相关资源
    最近更新 更多