简体   繁体   English

javascript中正则表达式,用于开始和结束处的特殊字符以及两个之间的连续字符不起作用

[英]Regular expression in javascript for Special characters at Start and End and two consecutive inbetween not working

My requirement is that i needs to perform the validation for the input text which should not allow the special characters at start and end of the word and also it shouldn't allow two consecutive special characters in between the word. 我的要求是我需要对输入文本执行验证,该输入文本不应在单词的开头和结尾处都允许使用特殊字符,并且也不允许在单词之间使用两个连续的特殊字符。

For the above mentioned requirement i have found the regex and tested it on regex101.com and it's coming correct but when i wrote in the javascript i am not able to get the desired results. 对于上述要求,我已经找到了正则表达式并在regex101.com上对其进行了测试,它是正确的,但是当我用JavaScript编写时,我无法获得所需的结果。

The snippets are as follows: 摘录如下:

$('input').bind('keypress', function (event) {  
var re = new RegExp("^[a-z0-9](?!.*?[^\na-z0-9]{2}).*?[a-z0-9]$");
var key = String.fromCharCode(!event.charCode ? event.which :  event.charCode);
if (key.match(re)) {
  alert("Successful match");
} else {
 alert("No match");
 return false;
}

}); });

<input type="text">

But every time i am getting the result as no match. 但是每次我得到的结果都不匹配。 I am not getting where i am getting wrong. 我没有走错地方。

Please help on this. 请帮忙。

The JSFiddle link is : Demo for the Regex JSFiddle链接是: Regex演示

Regex sample input - taken from some stackoverflow post 正则表达式示例输入-来自某些stackoverflow帖子

The issue was that you were matching on the most recent character the user inputted against the regex, rather than the whole value of the <input> . 问题是您正在匹配用户根据正则表达式输入的最新字符,而不是<input>的整个值。

Try this code instead: 请尝试以下代码:

$('input').bind('keypress', function(event) {
    var re = new RegExp("^[a-z0-9](?!.*?[^/\na-z0-9]{2}).*?[a-z0-9]$");
    // This is now set to the value of the whole <input> element
    var key = $('input').val()
    if (key.match(re)) {
        alert("Successful match")
    }
    else {
        alert("No match")
    }
})

JSFiddle JSFiddle

尝试这个。

^[a-z0-9](?!.*?[^\na-z0-9]{2}).*?[a-z0-9]$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM