正则表达式需要在字符串的开头匹配特殊字符 [英] Regex needed for matching special characters at start of string

查看:135
本文介绍了正则表达式需要在字符串的开头匹配特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要修改现有的正则表达式,以便在字符串值的开头支持特殊字符。

I require a modification to my existing regex to support special characters at the starting of a string value .

我目前有这个表达式:

/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+])[A-Za-z\d][A-Za-z\d!@#$%^&*()_+.]{7,63}$/

这接受8-64个字符之间的任何字符串,其中包含至少1个数字,字母表以及以下特殊符号:!@#$%^& *()_ +。

This accepts any string between 8-64 chars , which has atleast 1 number , alphabet and a special symbol from the following : !@#$%^&*()_+.

如何识别特殊字符输入值?

How do I get it to recognize special characters at the start of an input value ?

要匹配的字符串:

.abc@1234
*abc@1234
abc@1234.
a@b.c1234

谢谢

推荐答案

您需要删除 [A-Za-z \ n] 并替换 {7 ,63} {8,64}

使用

^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+])[A-Za-z\d!@#$%^&*()_+.]{8,64}$

请参阅演示

也许,您还想将添加回前瞻,以便它是还需要:

Perhaps, you also want to add the . back to the lookahead, so that it was also required:

^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+.])[A-Za-z\d!@#$%^&*()_+.]{8,64}$
                                         ^

为确保特殊符号不会立即发生,请添加a (?!。* [!@#$%^& *()_ +。] {2}) 负向前瞻

To make sure the special symbols do not occur in immediate succession, add a (?!.*[!@#$%^&*()_+.]{2}) negative lookahead:

^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+.])(?!.*[!@#$%^&*()_+.]{2})[A-Za-z\d!@#$%^&*()_+.]{8,64}$
                                            ^^^^^^^^^^^^^^^^^^^^^^^^

请参阅此演示

请注意,很多人会对使用如此长的正则表达式的可维护性问题大肆宣传。您可以将条件拆分为单独的代码段,也可以使用带注释的多行正则表达式:

Note that a lot of people here would scream about mainainability issue of using such a long regex. You can either split the conditions into separate pieces of code, or use a multiline regex with comments:

var rx = RegExp("^" + // Start of string
               "(?=.*[a-zA-Z])" + // Require a letter
               "(?=.*\\d)" + // Require a digit
               "(?=.*[!@#$%^&*()_+])" + // Require a special symbol
               "(?!.*[!@#$%^&*()_+.]{2})" + // Disallow consecutive special symbols
               "[A-Za-z\\d!@#$%^&*()_+.]{8,64}" + // 8 to 64 symbols from the set
               "$");

var re = RegExp("^" + // Start of string
               "(?=.*[a-zA-Z])" + // Require a letter
               "(?=.*\\d)" + // Require a digit
               "(?=.*[!@#$%^&*()_+])" + // Require a special symbol
               "(?!.*[!@#$%^&*()_+.]{2})" + // Disallow consecutive special symbols
               "[A-Za-z\\d!@#$%^&*()_+.]{8,64}" + // 8 to 64 symbols from the set
               "$", "gm");

var str = '.abc@1234\n*abc@1234\nabc@1234.\na@b.c1234\n*abc@1234\nabc@1234.\na@b.c1234\na@b.#c123\na@__c1234';
while ((m = re.exec(str)) !== null) {
  document.body.innerHTML += m[0] + "<br/>";
}

这篇关于正则表达式需要在字符串的开头匹配特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆