Finding a string in the middle of a path

≯℡__Kan透↙ 提交于 2019-12-08 15:44:39

Your formulas (both of them) reduce to

2nd \    =FIND("\",A2,FIND("\",A2)+1)

If you want to go to the "next" backslash, you have to +1 each starting postion in the loop.

If you are using FIND, much simpler to use SUBSTITUTE to replace the desired \ with a unique character and then FIND that character.

But even easier would be to split the string into an array, and then return the appropriate array element.

With Excel 2016 you have the FILTERXML function that can easily do this:

=INDEX(FILTERXML("<t><s>" & SUBSTITUTE(A2,"\","</s><s>") & "</s></t>","//s"),3)

Note that, because your string starts with a \, the index number for the desired element will be n+1 and not n (ie. 3 will return path2)

And there are other ways to do this for earlier excel versions.

You could try:

  1. Import in A1 the string "path1\path2\path3\path4\path5" - Remove the fırst "\"
  2. Select cell A1
  3. Go to Data tab - Data Tools - Text to Columns
  4. Select Delimited - Next
  5. Other end import "\" - Next
  6. Finish

Substitute each backslash with a string of spaces equal to the length of the original string then pick the piece you want.

=TRIM(MID(SUBSTITUTE(A2, "\", REPT(" ", LEN(A2))), LEN(A2)*1, LEN(A2)))    '<- path1
=TRIM(MID(SUBSTITUTE(A2, "\", REPT(" ", LEN(A2))), LEN(A2)*2, LEN(A2)))    '<- path2
=TRIM(MID(SUBSTITUTE(A2, "\", REPT(" ", LEN(A2))), LEN(A2)*3, LEN(A2)))    '<- path3
=TRIM(MID(SUBSTITUTE(A2, "\", REPT(" ", LEN(A2))), LEN(A2)*4, LEN(A2)))    '<- path4
=TRIM(MID(SUBSTITUTE(A2, "\", REPT(" ", LEN(A2))), LEN(A2)*5, LEN(A2)))    '<- path5

'alternates for first and last
=TRIM(LEFT(SUBSTITUTE(MID(A2, 2, LEN(A2)), "\", REPT(" ", LEN(A2))), LEN(A2)))    '<- path1
=TRIM(RIGHT(SUBSTITUTE(A2, "\", REPT(" ", LEN(A2))), LEN(A2)))    '<- path5

Say A1 contains:

junk\gjgherhg\3876iseugf\hviu4t\5432\happy\sad

so there is some junk before the first backslash. In A2 enter:

=TRIM(MID(SUBSTITUTE($A$1,"\",REPT(" ",999)),ROWS($1:1)*999-998,999))

and copy downwards:

If you are interested in a specific part, use the proper substitute for ROWS(). So to get the third element, use:

=TRIM(MID(SUBSTITUTE($A$1,"\",REPT(" ",999)),3*999-998,999))

NOTE:

If there is no "junk" before the first backslash, you will get a blank. So if you know there is no "junk" and you want to get path1, use:

=TRIM(MID(SUBSTITUTE($A$1,"\",REPT(" ",999)),2*999-998,999))

etc. If all you want is the positions of the backslashes, you can use SUBSTITUTE(). To get the position of the second backslash, use:

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