繁体   English   中英

使用 Javascript 的正则表达式从字符串中提取中间名和姓氏

[英]Extract the middle names and last name from the string using regex of Javascript

我需要提取中间名和姓氏

Elev: 7EBB49 (Dan Greg Järgenstedt <dan.greg.smith@manu.al.edu>)
Expected: Greg Järgenstedt

Elev: 6EBB49 (Dan Järgenstedt <dan.greg.smith@manu.al.edu>)
Expected: Järgenstedt

Elev: 6EBB49 (Järgenstedt <dan.greg.smith@manu.al.edu>)
Expected: Järgenstedt

Elev: 6EBB49 (<dan.greg.smith@manu.al.edu>)
Expected: 

试过

function getSNames(input) {
    const names = input.match(/(?<!\[)(?<=\s)\w+(?=\s)/g);
    return names ? names.join(' ') : '';
}

您可以使用

const names = input.match(/(?<!\(\p{L}+\s+|\p{L})\p{L}+(?:\s+\p{L}+)*(?=\s*<)/gu)

请参阅正则表达式演示 u标志启用 Unicode 类别类。

图案详情

  • (?<!\\(\\p{L}+\\s+|\\p{L}) - 紧靠左边,不能有(后跟 1+ 个字母,然后是一个或多个空格,或者只是一个字母 (this用作 Unicode 字边界)
  • \\p{L}+ - 一个或多个字母
  • (?:\\s+\\p{L}+)* - 零次或多次出现 1+ 空格,然后是 1+ 字母
  • (?=\\s*<) - 紧靠右侧,必须有 0+ 个空格,然后是<

疯狂就是这样说的。

我认为您一般无法“提取中间名和姓氏”。 如果您所拥有的只是“名称”,那么您就被它困住了。 无论你想出什么规则,我都会向你展示它行不通的地方。 例如

  • 我的名字是“Peter Valdemar Mørch”。 名字=Peter,中间名=Valdemar,姓氏=Mørch
  • 我有一个朋友叫 Jens Erik Redacted。 名字=Jens Erik,没有中间名,姓氏=已编辑。 每次网站说“Hi Jens”时,都会有点侮辱他,因为他不是“Jens”,而是“Jens Erik”。
  • 我还有一个朋友叫 Kristian von Hornsleth。 名字=Kristian,没有中间名,姓氏=von Hornsleth
  • 在中文中,姓在名之前。 例如(我不认识他)“王秀英”的英文拼写为“Wang Xiuying”。 firstname=Xiuying,没有中间名,lastname=Wang(注意他们是如何交换的

你所做的在一般情况下不起作用,尤其是在国际上。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM