Given a spreadsheet cell containing a string that consists of a hyphenated series of character segments, I need to extract the last segment.
For example, consider column A containing data strings like XX-XXX-X-XX-XX-G10
, where X
denotes any character. What formula would I need to place in column B to get G10
as a result?
A B
1 XX-XXX-X-XX-XX-G10 G10
I'm looking for a formula that could work in in Libre Office Calc, Open Office Calc, MS Excel, or Google Sheets.
In LibreOffice Calc and OpenOffice Calc, you can use a regular expression to determine the position of the text after the last
-
character:will return
15
if A1 containsXX-XXX-X-XX-XX-G10
.Now, you can use this value to get the text "behind" that position, using the RIGHT() function:
Split up on multiple lines:
I found simply solution:
that gives me G10 as the result too! It works because COL A always have 3 chars at the end!
Another possibility in LO Calc is to use the general purpose regular expression macro shown here: https://superuser.com/a/1072196/541756. Then the cell formula would be similar to JPV's answer:
It appears that you want the characters that appear at the end of a string, to the right of the last instance of a hyphen character,
"-"
.This formula, adapted from here, works in Excel, *Calc & Google Sheets:
Explanation:
SUBSTITUTE(A1,"-",new_string)
will find each hyphen ("-"
) in the original string from cellA1
and replace it with anew_string
.REPT(" ",LEN(A1))
is a string of repeated space characters (" "
), the same length as the original string in cellA1
.TRIM(RIGHT(string,count))
will get the right-mostcount
characters, and trim off leading and trailing spaces. Since the string was previously padded out by replacing hyphens with spaces, andcount
is the sameLEN(A1)
used for that padding, the lastcount
characters consists of a bunch of spaces followed by whatever followed the last hyphen!In Google Sheets, an alternative approach is to use the SPLIT function to break the value from column A into an array, then select the last element. (Excel-VBA has a
split()
function, so you could make this work in Excel by writing VBA code to provide it as a custom function.)If you are using google sheets, regexextract would be possible too: