将“姓氏的名字”更改为“姓氏,名字”

时间:2018-12-07 15:43:32

标签: r regex string

我有一个名称列表,需要将其从“名字的姓氏”转换为“名字的姓氏”。

Barack Obama
Donald J. Trump
J. Edgar Hoover
Beyonce Knowles-Carter
Sting

我用格罗腾迪克(G. Grothendieck)对"last name, first name" -> "first name last name" in serialized strings的回答得出了gsub("([^ ]*) ([^ ]*)", "\\2, \\1", str),这给了我-

Obama, Barack
J., DonaldTrump, 
Edgar, J.Hoover, 
Knowles-Carter, Beyonce
Sting

我想得到什么-

Obama, Barack
Trump, Donald J. 
Hoover, J. Edgar
Knowles-Carter, Beyonce
Sting

我想要一个正则表达式答案。

2 个答案:

答案 0 :(得分:5)

使用

gsub("(.*[^van])\\s(.*)", "\\2, \\1", people)

正则表达式:

(.*[^van])                                         \\s                      (.*)
Any ammount of characters exluding "van"...  the last white space...  The last name containing any character.

数据:

people <- c("Barack Obama",
            "Donald J. Trump",
            "J. Edgar Hoover",
            "Beyonce Knowles-Carter",
            "Sting",
            "Ruud van Nistelrooy",
            "Xi Jinping",
            "Hans Zimvanmer")

结果:

    [1] "Obama, Barack"           "Trump, Donald J."        "Hoover, J. Edgar"       
[4] "Knowles-Carter, Beyonce" "Sting"                   "van Nistelrooy, Ruud"   
[7] "Jinping, Xi"             "Zimvanmer, Hans" 

答案 1 :(得分:5)

有一个名为<?php include 'user.php'; $product = new User('products'); if(isset($_POST['productSubmit'])){ $porductData = array( 'category' => $_POST['kategorija'], 'name' => $_POST['naziv'], 'description' => $_POST['opis'], 'file_name_1' => $_POST['image_1'], 'file_name_2' => $_POST['image_2'], 'file_name_3' => $_POST['image_3'], 'file_name_4' => $_POST['image_4'], 'file_name_5' => $_POST['image_5'], ); $insert = $product->insert($porductData); } ?> 的深奥函数,用于保存名称,一个转换函数person会为您进行解析,然后是as.person方法来使用它(创造性地使用大括号参数)。它甚至可以使用复杂的姓氏(例如van Nistelrooy),但单个名字的结果并不令人满意。它可以通过快速结束format来解决。

sub