如何改进此电子邮件正则表达式以支持有效的有趣字符

时间:2013-12-03 12:02:16

标签: ruby regex

我在线查找了许多正则表达式,经过多次测试后,他们都无法匹配此电子邮件:

CAKyppebtX1Fe7t1bdZGABT1a9Pp4bp6zVnx=DA_69SwRpuBu4w@mail.gmail.com

我要做的是从一个文本块中提取电子邮件,而我所得到的只是=符号之后的部分:

str    = 'Foo: <CAKyppebtX1Fe7t1bdZGABT1a9Pp4bp6zVnx=DA_69SwRpuBu4w@mail.gmail.com>'
emails = str.scan(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)

=> ['DA_69SwRpuBu4w@mail.gmail.com']

2 个答案:

答案 0 :(得分:1)

您可以将=添加到正则表达式:

 str    = 'Foo: <CAKyppebtX1Fe7t1bdZGABT1a9Pp4bp6zVnx=DA_69SwRpuBu4w@mail.gmail.com>'
 emails = str.scan(/\b[A-Z0-9._%+-=]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)

 => ["CAKyppebtX1Fe7t1bdZGABT1a9Pp4bp6zVnx=DA_69SwRpuBu4w@mail.gmail.com"]

答案 1 :(得分:1)

在您用于用户名的字符类中包含=吗?

str    = 'Foo: <CAKyppebtX1Fe7t1bdZGABT1a9Pp4bp6zVnx=DA_69SwRpuBu4w@mail.gmail.com>'
emails = str.scan(/\b[A-Z0-9._%+-=]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)

=> ["CAKyppebtX1Fe7t1bdZGABT1a9Pp4bp6zVnx=DA_69SwRpuBu4w@mail.gmail.com"]