If you're using the latest version of mac or windows and you are using the
desktop version of Excel, you might be able to use the new REGEXREPLACE
function. If you're on web Office 365 like me, you may have to use something
like the beast below:
=IF(ISERROR(SEARCH(",*", J3,1)),J3,REPLACE(J3,SEARCH(",*",J3),LEN(J3)-SEARCH(",*",J3),""))
In this snippet, I am trying to replace ",.*$"
with ""
. In short, If there's
a comma in the field, I wish to remove the comma and everything after the comma.
I did this with REGEXREPLACE
in Google Sheets.
In Excel, I had to get tricky.
There's a REPLACE
function that can take text from one field and replace it
with other text, but it's bare-bones. You have to specify the index and length
of the substring to replace, along with the string with which to replace it.
There's also a SEARCH
function, which doesn't do regexes but does do
globbing, which is close and good enough for me. It returns the start index of
any matches to the pattern if such a match exists, and an error if it does not.
So I had to use ISERROR
to see if search found anything. If it didn't, I just
return the contents of the field which I wish to change. If it did find
something, I:
- Call
SEARCH("<PATTERN>",<FIELD>)
to get the index of the match
- Use that value to specify what index to start replacing text for
REPLACE
- Use that value to specify what index to end replacing text for
REPLACE
by
calculating LEN(<FIELD>)-SEARCH(...)
- Specify the replacement string
- Put all that stuff in a REPLACE function
I know it's involved, but hopefully helps some poor searching soul in the
future.
=
equals to sign? – Foulup