简体   繁体   English

正则表达式检测连字符

[英]Regex to detect hyphen character

Live demo: http://regex101.com/r/wW6wC4 现场演示: http//regex101.com/r/wW6wC4


I'm trying to add a regex expression that allows email addresses like: 我正在尝试添加一个允许电子邮件地址的正则表达式:

asdf.asdf@test-dom-a.com

([\w+\.]+@[\w]{1,})(\.)([0-9a-zA-Z\.\-]{1,})
                                     ^---- Thought this would allow hyphens...

what am I missing here? 我在这里想念的是什么?

Your pattern requires that the hyphen appears after a period. 您的模式要求在一段时间后出现连字符。 Try this instead: 试试这个:

([\w+.]+@[\w-]{1,})(\.)([0-9a-zA-Z.-]+)

Demonstration 示范

Or more simply: 或者更简单:

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

Although the second pattern doesn't require that the second part of the address contains a period. 虽然第二种模式不要求地址的第二部分包含句点。

Demonstration 示范

Your regex: 你的正则表达式:

([\w+\.]+@[\w]{1,})(\.)([0-9a-zA-Z\.\-]{1,})

This will allow hyphen as last character only. 这将仅允许连字符作为最后一个字符。

To allow it anywhere use: 允许它在任何地方使用:

^([\w+.-]+@[\w-])(\.)([0-9a-zA-Z.-])$

OR to allow it only in between use (except first and last position): 或者只允许使用之间 (第一个和最后一个位置除外):

^[\w+.-]*@\w[\w-]*\.[\w-]*[0-9a-zA-Z.]+$

Working Demo: http://regex101.com/r/lQ1nV7 工作演示: http//regex101.com/r/lQ1nV7

Your hyphen code appears in the segment that checks characters after the first period in the domain name. 您的连字符代码显示在域名中第一个句点之后检查字符的段中。 You need to add it to the match block before the domain name: 您需要在域名之前将其添加到匹配块:

([\w+\.]+@[\w\-]{1,})(\.)([0-9a-zA-Z\.\-]{1,})
             ^^----  check here as well.

In reality, I would search for a more comprehensive email regex - the one you have doesn't seem robust enough IMHO. 实际上,我会搜索更全面的电子邮件正则表达式 - 你拥有的那个看起来不够强大恕我直言。

You're not matching strings of the form "asd@fge.hj-kl", which as you can see not what you want. 你没有匹配“asd@fge.hj-kl”形式的字符串,因为你看不到你想要的。

([\w+\.]+)@([0-9a-zA-Z\.\-]{1,})\.com
([\w+\.]+)@([0-9a-zA-Z\.\-]{1,})\.([\w]{1,})

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

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