原谅提取名称和电子邮件正则表达式js

时间:2017-03-21 08:04:47

标签: javascript regex email

尝试为电子邮件地址解析创建一个宽容的正则表达式,到目前为止我已经

var regex = /(?:"?([A-Z][^<"]+)"?\s*)?<?([^>\s,]+)/gi;
var ip='"Bob Smith" <bob@company.com>, <joe@company.com>, "John Doe <john@company.com>, foo Bar <foo@company.com>, <abcd@efg.com>, Ln, Fn<fnln@domain.com>,"Mn, Gn"<gnmn@domain.com>,Nn, Hn <hnnn@domain.com>, bar@gmail.com, Rum@bacardi.com, In,On <onin@example.com>';
while (m = regex.exec(ip)) {
if (m[1]) {
    m[1] = m[1].trim()
}
extracts.push({
    name: m[1]?m[1]:m[2].replace(/@.*/,""),
    email: m[2]
});

匹配以下内容,

"Bob Smith" <bob@company.com>, <joe@company.com>, "John Doe <john@company.com>, foo Bar <foo@company.com>, <abcd@efg.com>, Ln, Fn<fnln@domain.com>,"Mn, Gn"<gnmn@domain.com>,Nn, Hn <hnnn@domain.com>

但是错过了这些,

bar@gmail.com, Rum@bacardi.com, In,On <onin@example.com>

代码

&#13;
&#13;
function paintExtracts(extracts) {
  var html = '<table border="1"><thead><tr><td>Name</td><td>Email</td></tr></thead><tbody>';
  for (var i = 0; i < extracts.length; i++) {
    html += '<tr><td>"' + extracts[i].name + '"</td><td>"' + extracts[i].email + '"</td></tr>';
  }
  html += '</tbody></table>';
  $('#opdiv').html('').append(html);
}
var regex = /(?:"?([A-Z][^<"]+)"?\s*)?<?([^>\s,]+)/gi
$('#parsebtn').click(function() {
  var extracts = [];
  var ip = $('#inputta').val();
  while (m = regex.exec(ip)) {
    if (m[1]) {
      m[1] = m[1].trim()
    }
    debugger;
    extracts.push({
      name: m[1]?m[1]:m[2].replace(/@.*/,""),
      email: m[2]
    });
  }
paintExtracts(extracts);
});
&#13;
table {
  font-family: monospace;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="inputta" rows="12" cols="65">"Bob Smith" <bob@company.com>, <joe@company.com>, "John Doe <john@company.com>
foo Bar <foo@company.com>, <abcd@efg.com>,
</textarea>
<p>
  <input type="button" id='parsebtn' value="Parse"></input>
  <div id="opdiv">
    <h1>
  Parsed Data
  </h1>
  </div>
&#13;
&#13;
&#13;

0 个答案:

没有答案