removing everything after first 'backslash' in a string

被刻印的时光 ゝ 提交于 2019-12-08 02:53:19

问题


I have a vector like below

vec <- c("abc\edw\www", "nmn\ggg", "rer\qqq\fdf"......)

I want to remove everything after as soon as first slash is encountered, like below

newvec <- c("abc","nmn","rer")

Thank you.

My original vector is as below (only the head)

[1] "peoria ave\nste \npeoria"                      [2]   "wood dr\nphoenix"                                  
"central ave\nphoenix"                            
[4] "southern ave\nphoenix"                         [5]   "happy valley rd\nste   
\nglendaleaz "               "the americana at brand\n americana way\nglendale"

Here the problem is my original csv file does not contain backslashes, but when i read it backslashes appear. Original csv file is as below

[1] "peoria ave               [2] "wood dr
     nste                          nphoenix"       
     npeoria"

As you can see, they are actually separated by "ENTER" but when i read it in R using read.csv() they are replaced by backslashes.


回答1:


another solution :

 sub("\\\\.*", "", x)



回答2:


vec <- c("abc\\edw\\www", "nmn\\ggg", "rer\\qqq\\fdf")
sub("([^\\\\])\\\\.*","\\1", vec)
[1] "abc" "nmn" "rer"



回答3:


strssplit(vec, "\\\\") should do the job.

TO select the first element [[1]][1] 2nd [[1]][2]



来源:https://stackoverflow.com/questions/17187552/removing-everything-after-first-backslash-in-a-string

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