【问题标题】:Single RegEx to support both Email and Alphanumeric string单个 RegEx 支持电子邮件和字母数字字符串
【发布时间】:2015-09-30 14:52:58
【问题描述】:

我正在使用以下两种模式

1 - 测试没有空格的字母数字和一些特殊字符,如'-'、'#'、'&'

var test =  /^([a-zA-Z0-9\.\-#&\s]{6,})*$/

A - test.test('Kumar'); // False (Since 6 characters are not there)

B - test.test('Bibek1211');//True

C - test.test('Bibek1211#-&');//True

D - test.test('Bibek12 Kumar');//False (Since space is there)

2 - 测试电子邮件

 var test =  /^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z](?:[A-Za-z]*[A-Za-z])?$/ 

现在我需要合并上述两个正则表达式并将其放入一个正则表达式中。这是我面临的问题,因为我对正则表达式知之甚少。

我想添加上述 2 个正则表达式并将其放在一个正则表达式中(在 c# 和 javascript 中),以便一个正则表达式能够验证以下模式

A - test.test('Kumar'); // False (Since 6 characters are not there)
B - test.test('Bibek1211');//True
C - test.test('Bibek1211#-&');//True
D - test.test('Bibek12 Kumar');//False (Since space is there)
E - test.test('Kumar@gmail.com');//True
F - test.test('Kumar@gmailcom');//False (Not an Email)

请帮我拿到上面的。提前致谢!!

【问题讨论】:

  • @Oceans 管道概念适用于 java 。它也适用于 c# 和 javascript 吗?
  • 正则表达式是正则表达式,所以同样可以应用。

标签: javascript c# regex


【解决方案1】:

下面的代码呢

^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z](?:[A-Za-z]*[A-Za-z])?$ |^([a-zA-Z0-9\.\-#&\s]{6,})*$

这可能是原图:https://www.debuggex.com/i/tK73IHD4OYz9mWAR.png

【讨论】:

    【解决方案2】:

    您可以简单地使用 |or 将 2 个正则表达式组合在一起。

    ^(?:(?:[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z](?:[A-Za-z]*[A-Za-z])?)|([a-zA-Z0-9\.\-#&]{6,}))$
    

    查看演示。

    https://regex101.com/r/iJ3dS6/1

    【讨论】:

    • 我们可以在 ASP.Net MVC 模型中使用不显眼的验证做同样的事情吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    相关资源
    最近更新 更多