Using gsub/regex to place quotes around names inside string

落爺英雄遲暮 提交于 2019-12-12 06:53:07

问题


I have tried searching, but cannot find the exact thing I am looking to do. My apologies if I have overlooked it. I am trying to take a long vector of character strings, all with the same general structure, and place them into a data.frame. The structure is as follows:

[1]   "rank, team, record"
[2]   "1 Team 22-4"
[3]   "2 Long Team Name 20-6"

My initial thought was to use gsub and a regex expression to place /" around the team names (ex. /"Long Team Name/") then use read.table to import, but I am running into difficulty coming up with the regex expression to do this. This would allow me to read in the string as tab delimited string, correct? If there is an easier suggestion, I am all ears.

Thanks! Brian


回答1:


I think this is what you want?

library(stringi)

x = c("rank, team, record", "1 Team 22-4", "2 Long Team Name 20-6")

res = stri_replace_first_fixed(x, " ", "|")
res = stri_replace_last_fixed(res, " ", "|")

res = stri_split_fixed(res, pattern = "|", simplify = T)
#      [,1]    [,2]             [,3]    
# [1,] "rank," "team,"          "record"
# [2,] "1"     "Team"           "22-4"  
# [3,] "2"     "Long Team Name" "20-6"  

The result is a matrix, but you could wrap it in as.data.frame.



来源:https://stackoverflow.com/questions/42684224/using-gsub-regex-to-place-quotes-around-names-inside-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!