Extract Last two Words from strings in cell

2 ビュー (過去 30 日間)
Muhammad Rahil Rafiq
Muhammad Rahil Rafiq 2020 年 3 月 2 日
編集済み: Stephen23 2020 年 3 月 3 日
A={'There is a world of good you could perform';
'All the money in the world couldnot have saved her';
'W';
'My world'}

採用された回答

dpb
dpb 2020 年 3 月 2 日
編集済み: dpb 2020 年 3 月 3 日
> arrayfun(@(s) s{:}(end-((numel(s{:})-1)>=1):end),arrayfun(@(s) split(s).',S,'uni',0),'uni',0)
ans =
4×1 cell array
{1×2 string}
{1×2 string}
{["W" ]}
{1×2 string}
>>
"what if we want to extract last three words instead of two words."
Actually, there's a much easier way to compute the starting position than above...
nW=3;
arrayfun(@(s) s{:}(max(numel(s{:})-(nW-1),1):numel(s{:})),arrayfun(@(s) split(s).',S,'uni',0),'uni',0)
Set nW first; to pass as argument to arrayfun would have to make it an array since it won't accept anything except an array as an argument...unfortunately, no automagic argument expansion for such purposes.
As noted, the regexp solution is undoubtedly the more better route for stuff like this...altho there's a notable difference in the two results -- this returns a cell array of the words separated out; the regexp result has a single phrase containing the number of words.
An alternate way with string functions would be to find() the last blank in the string before the right number of words and extractAfter. That would also return the substring in one piece.
  2 件のコメント
Muhammad Rahil Rafiq
Muhammad Rahil Rafiq 2020 年 3 月 3 日
It worked.
1- what if we want to extract last three words instead of two words.
2-While exporting the ans to excel (xlswrite), its displaying empty cells in excel
dpb
dpb 2020 年 3 月 3 日
It really was posted mostly tongue-in-cheek; this problem is probably most suited for regexp but I'm not fluent enough to be able to just write the proper expression otomh, sorry.
  1. Fix up the algebra to calculate start position from end -- it gets a litt bit messier but not impossible. Variable number to return would be simpler if flipped left-right and counted from beginning instead.
  2. xlswrite only writes rectangular regions in a single call or one has to convert so each element is in its on cell; that wasn't part of the initial requirement specifications, either! :)

サインインしてコメントする。

その他の回答 (1 件)

Stephen23
Stephen23 2020 年 3 月 3 日
編集済み: Stephen23 2020 年 3 月 3 日
>> A = {'There is a world of good you could perform'; 'All the money in the world couldnot have saved her'; 'W'; 'My world'}
A =
'There is a world of good you could perform'
'All the money in the world couldnot have saved her'
'W'
'My world'
>> C = regexp(A,'(\w+\s*){1,2}$','match','once')
C =
'could perform'
'saved her'
'W'
'My world'

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by