web-dev-qa-db-ja.com

jqueryを使用してバルクテキストからすべての電子メールアドレスを抽出する

私はこのテキストを下に持っています:

[email protected], "assdsdf" <[email protected]>, "rodnsdfald ferdfnson" <[email protected]>, "Affdmdol Gondfgale" <[email protected]>, "truform techno" <[email protected]>, "NiTsdfeSh ThIdfsKaRe" <[email protected]>, "akasdfsh kasdfstla" <[email protected]>, "Bisdsdfamal Prakaasdsh" <[email protected]>,; "milisdfsfnd ansdfasdfnsftwar" <[email protected]>

ここでは、メールは,または;。上記のすべての電子メールを抽出し、配列に保存します。正規表現を使用してすべてのメールを直接取得する簡単な方法はありますか?

33
Milind Anantwar

次の正規表現を使用できます。

var re = /(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))/g;

次のように電子メールを抽出できます。

('[email protected], "assdsdf" <[email protected]>, "rodnsdfald ferdfnson" <[email protected]>, "Affdmdol Gondfgale" <[email protected]>, "truform techno" <[email protected]>, "NiTsdfeSh ThIdfsKaRe" <[email protected]>, "akasdfsh kasdfstla" <[email protected]>, "Bisdsdfamal Prakaasdsh" <[email protected]>,; "milisdfsfnd ansdfasdfnsftwar" <[email protected]>').match(re);

//["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"]
12
Minko Gechev

受け入れられた答えの更新です。これは、電子メールアドレスの「プラス」記号では機能しません。 GMAILは[email protected]をサポートしています。

私はに更新しました:

return text.match(/([a-zA-Z0-9._+-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
8
Nick Caruso

そのためにjQueryは必要ありません。 JavaScript自体は、組み込みの正規表現をサポートしています。

JavaScriptで正規表現を使用する方法の詳細については、 正規表現 をご覧ください。

それ以外は、Stack Overflowのどこかであなたの質問に対する正確な答えが見つかると思います- javascriptの文字列から電子メールと名前を見つける方法

2
Roy Dictus
function GetEmailsFromString(input) {
  var ret = [];
  var email = /\"([^\"]+)\"\s+\<([^\>]+)\>/g

  var match;
  while (match = email.exec(input))
    ret.Push({'name':match[1], 'email':match[2]})

  return ret;
}

var str = '"Name one" <[email protected]>, ..., "And so on" <[email protected]>'
var emails = GetEmailsFromString(str)

ソース

2
Johan

以下の関数は、RFC2822Regexr.com に準拠しています

ES5:

var extract = function(value) {
   var reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g;
   return value && value.match(reg);
}

ES6:

const reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g
const extract = value => value && value.match(reg)

Regexrコミュニティソース

2
Sebastien H.