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

조회 수: 1 (최근 30일)
Elena
Elena 2022년 2월 24일
댓글: DGM 2022년 2월 25일
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.

채택된 답변

DGM
DGM 2022년 2월 24일
편집: DGM 2022년 2월 24일
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
Rik
Rik 2022년 2월 24일
mailhost1each=strrep(mailhost1each,'@earthlink.com','@earthlink.net');
DGM
DGM 2022년 2월 25일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by