更改字符串在 R 中较大字符串中的位置

Change the position of string within a larger string in R

我有一个字符列,看起来像这样:

names <- c("Isle North East", "London Northwestern", "Bedfordshire North East", "Southwark and Bermondsey North East",
           "Middlesbrough South and Cleveland East")

我想做的是将表达式 "North East" 移动到出现在它之前的任何单词之前。因此,如果字符串是 XXXX XXXX North East,我希望它是“XXXX North East XXXX”。如果我展示我正在寻找的解决方案,也许会更容易:

ideal.names <- c("North East Isle", "London Northwestern", "North East Bedfordshire", "Southward and North East Bermondsey",
             "Middlesbrough South and Cleveland East")

我正在尝试不同的方法,例如:

c(sub('^(.*) North East', 'North East \1', names))

但是这个returns以下:

[1] "North East Isle"                        "London Northwestern"                   
[3] "North East Bedfordshire"                "North East Southwark and Bermondsey"   
[5] "Middlesbrough South and Cleveland East"

所以问题在于,这会将字符串 North East 移动到字符串的开头,而不是在其前面的单词之前。所以我得到 North East Southwark and Bermondsey 而不是 Southward and North East Bermondsey,这正是我想要的。 任何帮助都会很棒。 谢谢!

您可以使用

gsub('(\S+) (North East)', '\2 \1', names)
## => [1] "North East Isle"                        "London Northwestern"                    "North East Bedfordshire"                "Southwark and North East Bermondsey"   
##    [5] "Middlesbrough South and Cleveland East"

详情

  • (\S+) - 第 1 组 (</code>):一个或多个非白人space</li> <li><code> - 一个space
  • (North East) - 第 2 组 (</code>):<code>North East 字符串。

参见regex demo