Excel, TEXT.RightPositionOf() - from FIND() to LAMBDA()
One of the days Frédéric LE GUEN suggested variant of function to find most right position of the character within the string. In discussion with him and Brad Yundt we generated several of variants, here they are.
As the sample, let try to find most right position of the slash in full filepath.
It's well known how to do that in pre-DA Excel, let try to use modern Excel functionality. One of first variants was like
=LET( str, A1, txt, "/", weDontHaveIt, UNICHAR(9999), txtCount, LEN(str) - LEN(SUBSTITUTE(str, txt, "")), k, SEQUENCE(txtCount), txtAppearance, SUBSTITUTE(str, txt, weDontHaveIt,k), txtPositions, FIND(weDontHaveIt, txtAppearance), INDEX(txtPositions, txtCount))
Coooool! But what if we'd like to find position of last "oo" here? If to try same way
=LET( str, A2, txt, "oo", weDontHaveIt, UNICHAR(9999), txtCount, (LEN(str) - LEN(SUBSTITUTE(str, txt, "")))/LEN(txt), k, SEQUENCE(txtCount), txtAppearance, SUBSTITUTE(str, txt, weDontHaveIt,k), txtPositions, FIND(weDontHaveIt, txtAppearance), INDEX(txtPositions, txtCount))
obviously it doesn't work
First in mind is to reverse texts and find first appearance of one into another
=LET(
str, A3,
txt, "oo",
strLength, LEN(str),
strReverse, TEXTJOIN("", 0, MID(str, SEQUENCE(LEN(str),,LEN(str),-1),1)),
txtReverse, TEXTJOIN("", 0, MID(txt, SEQUENCE(LEN(txt),,LEN(txt),-1),1)),
LEN(str) - FIND(txtReverse, strReverse))
Much better, now we have correct result
However, LET() only was yesterday, in addition now we have LAMBDA(). Still "limited edition", nonetheless. We may pack above code into the LAMBDA(), but it will be better to use recursion. As variant
=LAMBDA(str,txt, LET( strLength, LEN(str), txtLength, LEN(txt), IFS( strLength*txtLength=0, "ERROR: we can't find <" & txt & "> in <" & str & ">", TRUE, IF( RIGHT(str,txtLength) = txt, strLength-txtLength+1, TEXT.RightPositionOf(LEFT(str,strLength-1), txt) ) ) ))
which returns
Coooool, it works! Back to initial sample, filepath could be returned by
=LET( fullPath, CELL("filename"),
slash, IF(LEFT(fullPath,4)="http", "/", "\"),
IFERROR(
LEFT(fullPath, TEXT.RightPositionOf( fullPath, slash)),
"ERROR: We can't find file path")
)
Thanks for sharing