Regex / preg_match - 在字符串和电子邮件地址之间获取文本

时间:2017-02-22 00:20:03

标签: php regex preg-match

我正在从电子邮件中提取数据。我有这样的文字:

Eg. 1: some standard text.   Bugs Bunny bugs@gmail.com 0411111111 more standard text 
Eg. 2: some standard text.   Bugs The Bunny bugs@gmail.com 0411111111 more standard text
Eg. 3: some standard text.   Bugs Bunny bugs.bunny@gmail.com 0411111111 more standard text
Eg. 4: some standard text.   Bugs bugs.bunny@gmail.com +6141 111 111 more standard text

如您所见,我想提取一个名称,电子邮件和电话号码。 电子邮件应该很简单,我确信我可以解决手机选项,但我怎么能得到这个名字?

我知道逻辑是:在some standard text.之后和@之前的第一个非空格分隔字符串之前获取文本,但是如何?

这是我的出发点(?<=some standard text. )(.*?)(?=@)

这给了我一个小组(?<=some standard text. )(.*?)(?:[\w-\.]+)@的结果,所以我认为我走的是正确的道路。

我正在使用php。

2 个答案:

答案 0 :(得分:2)

这是我提出的快速版本/示例:

(?<=some standard text. )(.*?) ([^\s]+@[^\s]+) (\+?\d+(?:\s\d+)*) 

regex101.com/r/Wjz66g/1

它并不完美,但它确实遵循与您正在做的相同的方式,并且可能足够有效。

答案 1 :(得分:0)

我写了这个,您可以在https://regex101.com/r/A29hjE/8

上进行测试
(?x) # Here we are entering the the free space mode

# Here we assure the spaces are not matched by the `[\w ]+` group
(?:\.\s+)

# Here we are matching for the guys name, before its email address
([\w ]+(?:\w+))\s+

# Here we match the email
(\w[^\s]+@[^\s]+)\s+

# Here  we match the telephone number
(\+?[\d ]+)(?!\w)