【问题标题】:change position of word within a string in r在r中更改字符串中单词的位置
【发布时间】:2023-03-23 16:11:01
【问题描述】:

我有一个字符串向量,看起来像:

> string_vec
 [1] "XXX"                     "Snakes On A Plane"       "Mask of the Ninja"       "Ruslan"                 
 [5] "Kill Switch"             "Buddy Holly Story, The"  "Believers, The"          "Closet, The"            
 [9] "Eyes of Tammy Faye, The" "Gymnast, The"            "Hunger, The" 

有些名字最后包含“, The”。我想删除逗号和空格并将“The”移到所有其他文本之前。

例如:“Buddy Holly Story, The”变成“The Buddy Holly Story”。

用模式隔离记录很容易:

string_vec[grepl("[Aa-zZ]+, The", string_vec) == TRUE]

现在如何调整位置?

数据

string_vec <- c("XXX", "Snakes On A Plane", "Mask of the Ninja", 
"Ruslan", 
"Kill Switch", "Buddy Holly Story, The", "Believers, The", 
"Closet, The", 
"Eyes of Tammy Faye, The", "Gymnast, The", "Hunger, The")

【问题讨论】:

    标签: regex r string


    【解决方案1】:

    你可以试试

    sub('^(.*), The', 'The \\1', string_vec)
    #[1] "XXX"                    "Snakes On A Plane"      "Mask of the Ninja"     
    #[4] "Ruslan"                 "Kill Switch"            "The Buddy Holly Story" 
    #[7] "The Believers"          "The Closet"             "The Eyes of Tammy Faye"
    #[10] "The Gymnast"            "The Hunger"  
    

    【讨论】:

    • 这行得通!谢谢。我不知道 \\1 可用于引用 regex 中字符串中的位置。
    • @vagabond 我们正在捕获, The 之前的组并用它来替换\\1
    • @vagabond 这是括号内的第一个捕获组。假设如果有两个捕获组,我们将其称为\\1 \\2 等等。比如sub('^(.*), (The)', '\\2 \\1', string_vec),这里The是第二个捕获组
    • 如果您需要第一个单词,请尝试word(string_vec,1)sub('^(\\w+).*$', '\\1', string_vec)
    • @vagabond 或sub('[^A-Za-z]+.*$', '', string_vec)
    猜你喜欢
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多