Info

この質問は閉じられています。 編集または回答するには再度開いてください。

How to search for a specific string and only display the sentences that contains it.

1 回表示 (過去 30 日間)
Sam
Sam 2013 年 3 月 3 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
I have the following code
if strcmp('Hello', out)
*display only sentences with hello in them*
So my output should be only the sentences with hello in them. What function do I use?

回答 (1 件)

Sven
Sven 2013 年 3 月 3 日
編集済み: Sven 2013 年 3 月 3 日
Hi Sam,
regexp is the most flexible way to go:
testStrings = {'some text with hello','more with hello','nothing here','hello'}
regexp(testStrings,'.*hello.*','match','once')
ans =
'some text with hello' 'more with hello' '' 'hello'
There are lots of options such as case sensitivity (regexp() or regexpi()), including or not including any surrounding text (that's what the ".*" does).
Another way (less flexible, more simple) is to use strfind():
strfind(testStrings,'hello')
ans =
[16] [11] [] [1]
  2 件のコメント
Sam
Sam 2013 年 3 月 3 日
This is what I have so far while~feof(fid)
line=fgetl(fid);
if isempty(line)||strncmp(line, '%',1)||~ischar(line)
continue
end
out=regexp(line, ' ', 'split')
regexp(line,'.*hello.*','match','once')
end
But this just shows my the whole script.
Sven
Sven 2013 年 3 月 4 日
Your line:
out=regexp(line, ' ', 'split')
does nothing (ie, it's not ever used again) except it prints things to the screen. Either remove it or put a ";" after it.
line = 'This line has the word hello in it';
textWithHello = regexp(line,'.*hello.*','match','once');
if ~isempty(textWithHello)
disp(textWithHello)
else
disp('The line never had "hello" in it.'
end

この質問は閉じられています。

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by