2017-02-22 63 views
0

考虑下面的例子,我想获得的电子邮件地址正则表达式 - 获取组1“完全匹配”/0组

Eg. 1: some standard text. Bugs Bunny [email protected] 0411111111 more standard text 
Eg. 2: some standard text. Bugs The Bunny [email protected] 0411111111 more standard text 
Eg. 3: some standard text. Bugs-Bunny [email protected] 0411111111 more standard text 
Eg. 4: some standard text. Bugs [email protected] +6141 111 111 more standard text 
Eg. 5: some standard text. Bugs o'Bunny [email protected] 0411111111 more standard text 

这将做到这一点:(?<=some standard text. )(?:.*?)([^\s][email protected][^\s]+)https://regex101.com/r/A29hjE/9

但电子邮件地址是在组1中。我需要它是组0或完整匹配,因为这个正则表达式将由一些代码动态地创建,其中所有其他正则表达式都将他们的发现作为完整匹配产生。

我对组的了解不够,但我知道我需要some standard text.位后的第一个电子邮件地址,正如我所说的,它需要完全匹配。

回答

0

如果您将您的正则表达式更改为([^ \ s] + @ [^ \ s] +),则完整结果应该只是电子邮件地址。

+0

我得到的是,在实例给出,但我需要第一个电子邮件地址之后的一些标准文本,因为有全文的电子邮件地址。 – Warren

+0

基本上,您要求匹配“某些标准文本”,但不会在完整结果中显示该内容。我不相信这是可能的。 – dimab0

+0

我很害怕那个...... – Warren

0

组0 的完整赛票。

如果您将您的正则表达式更改为[^\s][email protected][^\s]+,那么它将与您所有示例中的电子邮件地址相匹配。 https://regex101.com/r/SQL9Ul/1

由于名称的长度不同,因此不能使用积极的lookbehind并匹配整个匹配的电子邮件地址。

0

你可以这样做:

$lines = array(
"some standard text. Bugs Bunny [email protected] 0411111111 more standard text ", 
"some standard text. Bugs The Bunny [email protected] 0411111111 more standard text", 
"some standard text. Bugs-Bunny [email protected] 0411111111 more standard text", 
"some standard text. Bugs [email protected] +6141 111 111 more standard text", 
"some standard text. Bugs o'Bunny [email protected] 0411111111 more standard text ", 
); 
foreach($lines as $line) { 
    preg_match('/some standard text..+?\K\[email protected]\S+/', $line, $m); 
    var_dump($m); 
} 

其中:

  • \K手段忘了所有我们遇到了,直到这里。
  • \S代表任何非空白,它是相同的是[^\s]

然后我们只有在$m[0]

输出电子邮件:

array(1) { 
    [0]=> 
    string(14) "[email protected]" 
} 
array(1) { 
    [0]=> 
    string(14) "[email protected]" 
} 
array(1) { 
    [0]=> 
    string(20) "[email protected]" 
} 
array(1) { 
    [0]=> 
    string(20) "[email protected]" 
} 
array(1) { 
    [0]=> 
    string(14) "[email protected]" 
}