简体   繁体   English

如何在正则表达式中添加空格字符

[英]How to add a blank space character to regular expression

I am using asp.net (c#) and for validation of an email address field, I have the following regular expression: 我正在使用asp.net(c#),并且为了验证电子邮件地址字段,我使用以下正则表达式:

[RegularExpression("^[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$"]

This works just fine except that when any leading/trailing white spaces are added to the email field, it throws an error as invalid email. 除了将任何前导/后缀空格添加到电子邮件字段时,它会作为错误的电子邮件引发错误,这一点很好。 How can I modify the regular expression in a way that it would accept such white spaces (later on in my code, I'll remove any spaces from either side so I store valid emails)? 如何修改正则表达式,使其可以接受这样的空格(在我的代码中,我将从任一侧删除所有空格,以便存储有效的电子邮件)? Thanks 谢谢

This doesn't sound right to allow spaces and you will trim off later, the regex is helping that scenario and providing that validation (although you should still check server side) 这听起来不适合允许空间,您稍后将进行精简,正则表达式正在帮助解决该情况并提供验证(尽管您仍应检查服务器端)

I think adding (\\\\s*) at the beginning and end should help you though. 我认为在开头和结尾添加(\\\\s*)应该可以帮助您。 ie

[RegularExpression("^(\\s*)[a-zA-Z0-9_\\.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}(\\s*)$")]

This is saying start or ends with whitespace 这是说以空格开头或结尾

Try this one 试试这个

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

This site also help https://regexr.com/ 这个网站也有帮助https://regexr.com/

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

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