简体   繁体   English

使用正则表达式验证JavaScript中的连续字符或数字?

[英]Regular Expression to validate on continuous character or numbers in JavaScript?

I need to validate if the string presents like continuous characters say like abc, def, ghi or 123,234,345,456 and so on using JavaScript, wants to through error or alert message. 我需要验证字符串是否以连续字符之类的形式出现,例如abc,def,ghi或123,234,345,456,等等,使用JavaScript,是否希望通过错误或警报消息。 Is there any possibilities with Match Patterns or Expression to validate such scenario. 匹配模式或表达式是否有可能验证这种情况。 Please if any come across, let me know asap. 如果有什么需要,请尽快告诉我。

Thanks in Advance!!! 提前致谢!!!

A regular expression is not the way to go for this one. 正则表达式不是实现此目的的方法。 Better will be to loop through all the characters in string checking if each is one greater than the last using str.charCodeAt() . 更好的方法是使用str.charCodeAt()循环检查字符串中的所有字符是否比最后一个大一个。

Regular expressions should not be used for this. 正则表达式不应用于此目的。 They don't "have memory", which means that you can't look for such sequences dynamically. 它们没有“拥有内存”,这意味着您无法动态查找此类序列。 Instead you would have to construct every possible acceptable sequence manually. 相反,您将必须手动构造每个可能的可接受序列

A better idea would be to use a for loop to run through your string and make the necessary assertions, like so: 更好的主意是使用for循环来遍历您的字符串并进行必要的断言,如下所示:

for (var i = 0; i < str.length; ++i) {
    if (str.charCodeAt(i) === str.charCodeAt(i + 1) - 1 &&
        str.charCodeAt(i) === str.charCodeAt(i + 2) - 2) {
        var ret = str.substr(i, i + 3);
        // do whatever you want to do with the match
    }
}

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

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