gpt4 book ai didi

regex - 更改r中字符串中单词的位置

转载 作者:行者123 更新时间:2023-12-04 14:11:37 24 4
gpt4 key购买 nike

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

> 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”变为“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")

最佳答案

你可以试试

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"

关于regex - 更改r中字符串中单词的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30055961/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com