与模式匹配的正则表达式,或者是空字符串 [英] Regular expression which matches a pattern, or is an empty string
问题描述
我有以下正则表达式与电子邮件地址格式匹配:
I have the following Regular Expression which matches an email address format:
^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$
这用于使用JavaScript进行表单验证。但是,这是一个可选字段。因此,如何更改此正则表达式以匹配电子邮件地址格式或空字符串?
This is used for validation with a form using JavaScript. However, this is an optional field. Therefore how can I change this regex to match an email address format, or an empty string?
从我有限的正则表达式知识,我认为 \ b
匹配一个空字符串, |
表示或,所以我尝试执行以下操作,但它不起作用:
From my limited regex knowledge, I think \b
matches an empty string, and |
means "Or", so I tried to do the following, but it didn't work:
^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$|\b
推荐答案
要匹配模式
或空字符串,请使用
To match pattern
or an empty string, use
^$|pattern
说明
-
^
和$
分别是字符串锚点的开头和结尾。 -
|
用于表示替代项,例如this | that
。 ^
and$
are the beginning and end of the string anchors respectively.|
is used to denote alternates, e.g.this|that
.- regular-expressions.info/Anchors and Alternation
- 连续之间
\ w
和\ W
(任一订单):
- 即在单词字符和非单词字符之间
- Between consecutive
\w
and\W
(either order):- i.e. between a word character and a non-word character
- ie在字符串的开头,如果它以
\w
- i.e. at the beginning of the string if it starts with
\w
- ie在字符串的末尾,如果它以
\w
- i.e. at the end of the string if it ends with
\w
- regular-expressions.info/Word Boundaries
根据规格,这不是一件小事。
This is not trivial depending on specification.
- What is the best regular expression for validating email addresses?
- Regexp recognition of email address hard?
- How far should one take e-mail address validation?
这篇关于与模式匹配的正则表达式,或者是空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
Explanation
大多数风格的 \ b
是一个单词边界锚点。它是零宽度匹配,即空字符串,但它只匹配非常特定位置的字符串,即在单词的边界处。
\b
in most flavor is a "word boundary" anchor. It is a zero-width match, i.e. an empty string, but it only matches those strings at very specific places, namely at the boundaries of a word.
即 \b
位于: