代码之家  ›  专栏  ›  技术社区  ›  kaka1234

Javascript Regex在开始和结束处限制下划线

  •  2
  • kaka1234  · 技术社区  · 6 年前

    我有一个表单,我想限制第一个和最后一个字符。(javascript) 限制是:

    • 输入必须以字母数字开始和结束,而不是下划线,字母数字之间只允许下划线。

     Valid Entries: abc, ABC, Abc123, 123a, Abc_12, Abc_12_3a
     Invalid Entries: _abc, abc_, _abc_
    

    我试图创建我的正则表达式如下:

    ^(?!\_)(?!_*_$)[a-zA-Z0-9_]+$
    

    这不允许在开头加下划线,这很好,但允许在结尾加下划线,这是我想要限制的。

    这里有什么遗漏。


    const validEntries = ['abc', 'ABC', 'Abc123', '123a', 'Abc_12', 'Abc_12_3a'];
    const invalidEntries = ['_abc', 'abc_', '_abc_'];
    
    const regex = /^(?!\_)(?!_*_$)[a-zA-Z0-9_]+$/;
    
    validEntries.forEach((x) => {
      const ret = regex.test(x);
      
      console.log('Should be true :', ret);
    });
    
    console.log('-------------------');
    
    invalidEntries.forEach((x) => {
      const ret = regex.test(x);
      
      console.log('Should be false :', ret);
    });

    ---更新---

    我在angularjs应用程序中使用regex。

    我已将我的指令创建为:

           .directive('restrictField', function () {
        return {
            require: 'ngModel',
            restrict: 'A',
            link: function (scope, element, attrs, ctrl) {
    
                var regReplace,
                    preset = {                   
                        'alphanumeric-spl': '\\w_./\s/g',
                        'alphanumeric-underscore': '\\w_',
                        'numeric': '0-9',
                        'alpha-numeric': '\\w'
                    },
                    filter = preset[attrs.restrictField] || attrs.restrictField;                
    
                ctrl.$parsers.push(function (inputValue) {
                    regReplace = new RegExp('[^' + filter + ']', 'ig');
                    if (inputValue == undefined)
                        return ''
                    cleanInputValue = inputValue.replace(regReplace, '');
                    if (cleanInputValue != inputValue) {
                        ctrl.$setViewValue(cleanInputValue);
                        ctrl.$render();
                    }
                    return cleanInputValue;
                });
            }
        }
    })
    

     <input type="text" name="uname" ng-model="uname" required class="form-control input-medium" restrict-field="alphanumeric-underscore" ng-trim="false" />  
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   Wiktor Stribiżew    6 年前

    您可以添加另一个负面展望( (?!.*_$)

    ^(?!_)(?!.*_$)[a-zA-Z0-9_]+$
    

    看到了吗 regex demo (?!.*_$) _ 在绳子的末端。

    ^[a-zA-Z0-9]([a-zA-Z0-9_]*[a-zA-Z0-9])?$
    ^[a-zA-Z0-9](\w*[a-zA-Z0-9])?$
    

    看到了吗 another regex demo . 此模式匹配:

    • ^ -字符串开头
    • [a-zA-Z0-9]
    • ([a-zA-Z0-9_]*[a-zA-Z0-9])? -一个可选的序列
      • [a-zA-Z0-9_]* \w*
    • $ -字符串结尾。

    关于编辑

    preset 应该包含要在中使用的模式 replace \w 比赛 :

    'alphanumeric-spl': '[^\\w\\s./]+', // Removes all but alnum, _ . / whitespaces
    'alphanumeric-underscore': '^_+|_+$|_+(?=_)|\\W+', // Removes all _ at start/end and all _ before a _ and all but alnum and _
    'numeric': '[^0-9]+',  // Removes all but digits
    'alpha-numeric': '[\\W_]+'  // Removes all but alnum
    

    regReplace = new RegExp(filter, 'ig');