regexp:FirstName LastName(domain.com)

时间:2014-04-29 20:16:03

标签: regex

我想创建一个正则表达式,但遗憾的是我的想法并不奏效 正则表达式应该只允许输入由两部分组成的字符串: 第一部分:字母(a-z,a-Z),数字(0-9)字符:点,短划线 第二部分:应该用括号开头和结尾,它们之间只允许:小写字母(a-z)和点

有效示例:

  1. John Smith(contoso.com) - >在这种情况下,第一部分是#34; John Smith",第二部分是"(contoso.com)"
  2. Jerry A. Doe(mail.com) - >在这种情况下,第一部分是" John A. Doe",第二部分是"(mail.com)"
  3. 信息(mydomain.com) - >在这种情况下,第一部分是"信息",第二部分是"(mydomain.com)"
  4. Mary-Jane(mydomain.com) - >在这种情况下,第一部分是 " Mary-Jane",第二部分是"(mydomain.com)"
  5. 没有匹配的例子:

    • John Smith
    • John Smith contoso.com
    • John Smith(Contoso.com)
    • Mary_Jane(mydomain.com)

    我的想法:

    [a-zA-Z0-9\s\.][\(][a-zA-Z0-9\.][\)]
    

3 个答案:

答案 0 :(得分:3)

您需要在角色类之后添加重复:

[a-zA-Z0-9\s.\-]+\([a-z.]+\)

我还做了一些其他的小改动,没有必要在字符类中放置\(\),也不需要在字符类中转义.。你还说你希望第一组允许破折号,所以我把它添加到角色类。

答案 1 :(得分:1)

你忘记了第一个冲刺。你只说小写字母和第二个中的点,所以删除大写和第二个中的数字。

[a-zA-Z0-9\s.-]+\([a-z.]+\)

最后,就像F.J.说的那样,你需要添加回复。 + 表示" 1次或更多次"。

请记住选择其中一个答案作为您接受的答案。

答案 2 :(得分:0)

这对你有用:

^([A-Za-z.\s-]+) (\([a-z.]+\))$

DEMO

http://regex101.com/r/gR5kN1

<强> 说明:

^ assert position at start of a line
1st Capturing group ([A-Za-z.\s-]+)
[A-Za-z.\s-]+ match a single character present in the list below
Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
A-Z a single character in the range between A and Z (case sensitive)
a-z a single character in the range between a and z (case sensitive)
. the literal character .
\s match any white space character [\r\n\t\f ]
- the literal character -
  matches the character   literally
2nd Capturing group (\([a-z.]+\))
\( matches the character ( literally
[a-z.]+ match a single character present in the list below
Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
a-z a single character in the range between a and z (case sensitive)
. the literal character .
\) matches the character ) literally
$ assert position at end of a line