如何阅读正则表达式在我的电子邮件验证

本文关键字:电子邮件 验证 我的 何阅读 正则表达式 | 更新日期: 2023-09-27 18:16:26

我找到了一个解决方案与正则表达式如何验证电子邮件。但我真的不明白如何正确地阅读它,因为这是我第一次使用正则表达式。有人能告诉我怎么用文字读吗?因为用if语句创建这个会很麻烦。

我的代码:
if (string.IsNullOrWhiteSpace(textBox4.Text))
{
    label8.Text = "E-pasts netika ievadīts!";
}
else
{
    Regex emailExpression = new Regex(@"^[a-zA-Z]['w'.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9]['w'.-]*[a-zA-Z0-9]'.[a-zA-Z][a-zA-Z'.]*[a-zA-Z]$");
    if (emailExpression.IsMatch(textBox4.Text))
    {
        label8.Text = "";
    }
    else
    {
        label8.Text = "E-pasts ievadīts nepareizi!";
    }
}

如何阅读正则表达式在我的电子邮件验证

对于正则表达式,请遵循链接:http://www.regexr.com/

粘贴你的正则表达式[a-zA-Z]['w'.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9]['w'.-]*[a-zA-Z0-9]'.[a-zA-Z][a-zA-Z'.]*[a-zA-Z]

将鼠标悬停在每个文本上,您将获得它们的含义

几个例子:

a-z将匹配a到z范围内的字符

A-Z将匹配A-Z范围内的字符

'w匹配任何单词字符

{2,28}匹配前一个标记

分类如下:只需注意所有[ ]都是单个项目的集合,以下可以是*(零次或多次),+一次或多次或{ , }(最小和最大)出现。

如果一个注释模式来显示一个固有的模式,它实际上更容易理解,一旦在关键点上加标签;我将这样做:

var pattern = @"
^                  # Beginning of line, data must start here instead of matching any location *away from the start*.
      [a-zA-Z]         # A set of characters from a-z and A-Z but just one
      ['w'.-]{2,28}    # A set of any word character 'w=a-zA-Z0-9 with a literal period and dash; but minimum of 2 to a max of 28 characters. 
      [a-zA-Z0-9]      # Could be replaced with a single 'w; this ensure that there is a character and not a non character before the @
  @                # Literal `@`
      [a-zA-Z0-9]      # same as 'w; ensures a character
      ['w'.-]*         # '*' = Zero or more of the set with a literal period in the set.
      [a-zA-Z0-9]      # same as 'w; ensures a character
 '.                # Literal Period must be matched.
      [a-zA-Z]         # A set of characters from a-z and A-Z but just one
      [a-zA-Z'.]*      # zero or more characters with a literal period `.`.
      [a-zA-Z]         # same as 'w; ensures a character
$                  # End; contrains the whole match with the `^` so no loose characters are left out of the match
";
// IgnorePatternWhitespace allows us to comment the pattern; does not affect processing in any way.
Regex.IsMatch("abcd@def.com", pattern, RegexOptions.IgnorePatternWhitespace); // True/Valid
Regex.IsMatch("1abcd@def.com", pattern, RegexOptions.IgnorePatternWhitespace);// False/Invalid
Regex.IsMatch("abc@def.com", pattern, RegexOptions.IgnorePatternWhitespace);  // False/Invalid

注意,在测试#3中发现的模式中有一个逻辑缺陷。For abc@def.com会失败,因为模式在@之前的第一个字符和最后一个字符前缀之间查找至少2个字符。我将把它改为*,这意味着零或更多。