2017-02-22 62 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]" 
}