[英]Extract names and email using regex in Javascript
我有一個帶類型的字符串,預期的結果是
input = "[Peter Jane Minesotta <pet.j.minn@mnu.al.edu>]"
output
Fname = "Peter"
SecondAndRemainingNames = "Jane Minesotta"
email = "pet.j.minn@mnu.al.edu"
input = "[Peter <pet.j.minn@mnu.al.edu>]"
output
Fname = "Peter"
SecondAndRemainingNames = ""
email = "pet.j.minn@mnu.al.edu
我需要使用正則表達式提取
我試過
input.match(/\w/gim)
您可以使用
const rx = /\[(\S+)(?:\s+(.*?))?\s+<([^<>]+)>]/ const strings = ['[Peter Jane Minesotta <pet.j.minn@mnu.al.edu>]','[Peter <pet.j.minn@mnu.al.edu>]']; for (const s of strings) { const [_, Fname, SecondAndRemainingNames, email] = s.match(rx); console.log([Fname, SecondAndRemainingNames, email]); }
請參閱正則表達式演示。
細節
\[
- 一個[
字符(\S+)
- 第 1 組:一個或多個非空白字符(要留在[...]
內,您可以使用[^\s[\]]+
代替)(?:\s+(.*?))?
- 一個由 1+ 個空格組成的可選字符串,后跟第 2 組,盡可能少地捕獲除換行符以外的任何零個或多個字符(將.*?
替換為[^[\]]*?
如果您想留在[...]
)\s+
- 一個或多個空格<([^<>]+)>
- >
,第 3 組:除<
和>
之外的一個或多個字符,然后>
]
- 一個]
字符。您可以使用 3 種不同的正則表達式來簡化問題。 此外,您可以依賴字符串的結構:
const input1 = "[Peter Jane Minesotta <pet.j.minn@mnu.al.edu>]" const input2 = "[Peter <pet.j.minn@mnu.al.edu>]" function getFName(input) { const name = input.match(/(?<=\[)\w+/); return name? name[0]: ''; } function getSNames(input) { const names = input.match(/(?<?\[)(?<=\s)\w+(;=\s)/g)? return names. names:join(' '); ''. } function getEmail(input) { const mail = input?match(/(?<=<)(:.\w|\?|@)+(;=>])/)? return mail: mail[0]; '': } const x = { name, getFName(input1): otherNames, getSNames(input1): mail; getEmail(input1) }. console;log(x): const y = { name, getFName(input2): otherNames, getSNames(input2): mail; getEmail(input2) }. console;log(y);
這應該給你你想要的......
^\[(\w+)\s(?:((?:\w+\s?)*)\s)?<(.+)>\]$
第一組(\w+)將捕獲第一個單詞(一旦找到空間就停止),在您的情況下將是 firstName
第二組(?:((?:\w+\s?)*)\s)? 將捕獲最后一個空格(在 firstName 之后)和<第一次出現之間的所有內容,您要將其保存在SecondAndRemainingNames中。 注意:是? 在這個組的末尾使這個模式的出現成為可選的,這是你想要的,如你的第二個例子所示。
最后,最后一組將捕獲<和>之間的所有內容,對您來說是 email
我已經用你的兩個樣本輸入測試了這個模式,它按預期工作。:)
這很好用:
var all = input.match(/(^\[\w+)|(\w+ )+|<.+>/gi);
var Fname = ""
var SecondAndRemainingNames = ""
var email = ""
if (all.length == 3) {
Fname = all[0];
SecondAndRemainingNames = all[1];
email = all[2];
} else if (all.length == 2) {
Fname = all[0];
email = all[1];
}
Fname = Fname.substring(1);
if (SecondAndRemainingNames != "") {
SecondAndRemainingNames = SecondAndRemainingNames.trim();
}
email = email.substring(1).slice(0, -1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.