Clear Filters
Clear Filters

how to extract a value with a specific character out of an character array

4 views (last 30 days)
a great example to describe this would be for emails. Say we have an input of:
emails = 'someone, random@gmail, other'
how would one know to select the one with the @gmail and then add the .com to the end after?
If there are multiple emails in the array, only display the first one.

Accepted Answer

DGM
DGM on 24 Feb 2022
Edited: DGM on 24 Feb 2022
I'm not sure which extra emails should be rejected. I'm going to assume that all other emails get rejected
emails = {'someone, random@gmail, backupaccount@yahoo, other';
'someone else, random2@hotmail, other'};
mailhost = regexp(emails,'@[^,]*','match');
mailhost1all = [mailhost{1}{1} '.com']
mailhost1all = '@gmail.com'
If instead there might be more than one email per entry in the emails array, and you only want the first email per entry in the array:
mailhost1each = cell(numel(emails),1);
for acct = 1:numel(emails)
mailhost1each{acct} = [mailhost{acct}{1} '.com'];
end
mailhost1each
mailhost1each = 2×1 cell array
{'@gmail.com' } {'@hotmail.com'}
  3 Comments
DGM
DGM on 25 Feb 2022
Maybe something like this?
emails = {'someone, random@gmail, backupaccount@yahoo, other';
'someone else, random2@earthlink, other'};
% match the whole email address
mailaccounts = regexp(emails,'[^,\s]*?@[^,]*','match');
% these hosts should be .net
hasnettld = {'earthlink','comcast','airmail','charter'};
hasnettld = cellfun(@(x) ['@' x],hasnettld,'uniform',false);
firstmailaccounts = cell(numel(emails),1);
for acct = 1:numel(emails)
thisacct = mailaccounts{acct}{1};
if contains(thisacct,hasnettld)
firstmailaccounts{acct} = [thisacct '.net'];
else
firstmailaccounts{acct} = [thisacct '.com'];
end
end
firstmailaccounts
firstmailaccounts = 2×1 cell array
{'random@gmail.com' } {'random2@earthlink.net'}
I'm sure this can be simplified, but I'm still not really sure what you want matched.

Sign in to comment.

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!