Excel: Returning characters to the left and right of the last (or second to last) occurrence?

纵饮孤独 提交于 2021-01-29 20:44:04

问题


I have a string like this: 100 Stupid Street ; Government Tower 7; Chicago Palm, MA 92111

I want to return all the characters to the left of the last semicolon.

To the left of the last semicolon would be: 100 Stupid Street ; Government Tower 7


That was step 1. I would also like to extract characters from this string: Chicago Palm, MA 92111

I want to return all the characters to the right and left of the second to last space.

So, To the right of the second to last space would be: MA 92111

To the left of the second to last space would be: Chicago Palm,

If there is a way to remove that last comma in that last formula, that would be even better.


This formula has helped me a bit:

=TRIM(RIGHT(SUBSTITUTE(A1,";",REPT(" ",LEN(A1))),LEN(A1)))

Cell A1 has the original string. This formula successfully returns everything to the right of the last semicolon.


回答1:


If you are looking to parse out all of the pieces, some of the previous returns can assist in the next operation(s) so portions of formulas do not have to be repeated.

    stupid street

B1 is =LEFT(SUBSTITUTE(A3, ";", "×",LEN(A3)-LEN(SUBSTITUTE(A3,";",""))), FIND("×",SUBSTITUTE(A3&"×", ";", "×",LEN(A3)-LEN(SUBSTITUTE(A3,";",""))))-1)

B2 is =TRIM(RIGHT(SUBSTITUTE(A2,";",REPT(" ",99)),99))

B3 is =TRIM(RIGHT(SUBSTITUTE(A3,",",REPT(" ",99)),99))

B4 is =TRIM(SUBSTITUTE(SUBSTITUTE(A4,B3,""),",",""))




回答2:


A shorter version:

B1      =LEFT(A1,(FIND(";",A1,FIND(";",A1)+1))-1)               ==> 100 Stupid Street ; Government Tower 7
B2      =TRIM(RIGHT(A1,LEN(A1)-FIND(";",A1,FIND(";",A1)+1)))    ==> Chicago Palm, MA 92111
B3      =LEFT(B2,FIND(",",B2)-1)                                ==> Chicago Palm
B4      =TRIM(RIGHT(B2,LEN(B2)-(FIND(",",B2)+1)))               ==> MA 92111

More generic:

B1   =LEFT(A1,(FIND("^",SUBSTITUTE(A1,";","^",LEN(A1)-LEN(SUBSTITUTE(A1,";","")))))-1)

And performing substitutions can be achieved otherwise. Homework.



来源:https://stackoverflow.com/questions/26704318/excel-returning-characters-to-the-left-and-right-of-the-last-or-second-to-last

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