简体   繁体   中英

How do you extract characters from a string?

I want to send emails from my google sheet. I want the emails to address recipients by their first name or the name they are known by. The following is an example of my data in column A.

样本数据

I need a formula in column B that extracts the first name from column A but if they are known by a different name, the name in the brackets in column A, then I want that name extracted to column B instead. I have the following formula which works for names in brackets but I need help with the formula to extract the first name when there are no brackets.

=(SPLIT(REGEXEXTRACT(A2,"\((.*)\)"),","))

Try this. In B2, enter this formula:

=iferror(SPLIT(REGEXEXTRACT(A2,"\((.*)\)"),","), mid(A2, find(", ", A2)+2, len(A2)))

Explanation:

The first part is yours: SPLIT(REGEXEXTRACT(A2,"((.*))"),",")

As you've seen, this returns an #ERROR if the "(" isn't found. So use iferror to wrap that. The second part is returned if there is an error: =mid(A2, find(", ", A2)+2, len(A2))

The mid() function returns a substring from a string. The first argument is the string that you're looking in, found in A2 . Then, The starting position of the substring is the location of ", " (offset by 2), and continues to the end of the string.

one-cell solution:

=ARRAYFORMULA(IFNA(IFNA(
 REGEXEXTRACT(A2:A, "\((.*)\)"), 
 REGEXEXTRACT(A2:A, ", (.*)"))))

0

Try this. In B1, enter this formula:

={"Salutation";arrayformula(if(A2:A="","",iferror((SPLIT(REGEXEXTRACT(A2:A,"\((.*)\)"),",")),index(split(A2:A," "),,2))))}

Explanation:

The first part is yours: SPLIT(REGEXEXTRACT(A2,"((.*))"),",")

As you've seen, this returns an #ERROR if the "(" isn't found. So use iferror to wrap that. The second part is returned if there is an error: index(split(A2:A," "),,2)

The index() function returns the second column from the split(). The advantage to doing it this way is you will not have to drag formulas down.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM