与模式匹配的正则表达式,或者是空字符串 [英] Regular expression which matches a pattern, or is an empty string

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

问题描述

我有以下正则表达式与电子邮件地址格式匹配:

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

  • Explanation

    • ^ 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

      大多数风格的 \ 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 位于:


      • 连续之间 \ w \ W (任一订单):


        • 即在单词字符和非单词字符之间

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