Warm tip: This article is reproduced from stackoverflow.com, please click
excel excel-formula search string position

MS Excel Formula: Find Position/Location of a Word in a String

发布于 2020-04-05 00:24:42

Using a MS Excel Formula (Not VBA), I would like to find the actual position/location of a specific word found within a String. If this is possible, I'd like to use a "Search and/or Replace" versus "Find or Substitute" function, as the text string is not an absolute by letter casing.

Cell A1 (Text String): "The dog ran behind the house and then jumped the fence."
Cell B1: (Target Keyword): Ran
Cell C1 (Position of Word): 3

Thanks in advance for your assistance.

Questioner
Miaka3
Viewed
47
JvdV 2020-02-02 17:58

The following would give you the word-index of the first word that contains your substring:

=SEARCH(B1,A1)-LEN(SUBSTITUTE(LEFT(A1,SEARCH(B1,A1))," ",""))+1

If you have access to FILTERXML you can retrieve it by throwing in some MATCH and this would return the word-index of an exact match:

=MATCH(B1,FILTERXML("<t><s>"&SUBSTITUTE(A1," ","</s><s>")&"</s></t>","//s"),0)

Note: The second formula needs to be entered through CtrlShiftEnter

As per @BigBen, you might run into troubled water if your string holds special characters like comma and the likes. In that case, you might want to throw in more nested SUBSTITUTE formulas to take care of that scenario.


If you need multiple matches, and you want it concatenated into a single cell, you'll need access to the TEXTJOIN function. To get all word-indexes of words that contain your substring:

=TEXTJOIN(", ",TRUE,IF(ISNUMBER(SEARCH(B1,FILTERXML("<t><s>"&SUBSTITUTE(A1," ","</s><s>")&"</s></t>","//s"))),ROW(A1:INDEX(A:A,LEN(A1)-LEN(SUBSTITUTE(A1," ","")))),""))

To get all exact matches that hold your lookup value:

=TEXTJOIN(", ",TRUE,IF(FILTERXML("<t><s>"&SUBSTITUTE(A1," ","</s><s>")&"</s></t>","//s")=B1,ROW(A1:INDEX(A:A,LEN(A1)-LEN(SUBSTITUTE(A1," ","")))),""))

Note: Both formulas needs to be entered through CtrlShiftEnter