how to combine strfind and index in one line?

조회 수: 2 (최근 30일)
raym
raym 2017년 3월 3일
편집: Walter Roberson 2017년 3월 3일
I tried to run strfind(argument,argument)(1) to return the first hit position, but matlab returns a error. It seems that I need to split the command into two lines? right?Is there any other way to make it in one line?

채택된 답변

Walter Roberson
Walter Roberson 2017년 3월 3일
second_last = @(V) V(end-1);
positionLast2nd = second_last(strfind(newname, '_'));
It is possible to do it without the helper function, but it really is not worth doing except to prove that you can, because the code gets obscure.

추가 답변 (2개)

Chad Greene
Chad Greene 2017년 3월 3일
편집: Chad Greene 2017년 3월 3일
You could use regexp with the 'once' option. For example, for this string:
str = ['Soldiers! Don''t give yourselves to brutes - men who despise you, enslave you, who '...
'regiment your lives, tell you what to do, what to think or what to feel! Who drill you,'...
'diet you, treat you like cattle, use you as cannon fodder.']
Each instance of the word you begins at the following indices:
regexp(str,'you')
ans =
22 61 74 92 109 166 176 187 208
If you only want the first instance use the 'once' option:
regexp(str,'you','once')
ans =
22
  댓글 수: 2
raym
raym 2017년 3월 3일
편집: Walter Roberson 2017년 3월 3일
Hi,Chad.
Thanks a lot.
Dose regexp has other options to retrieve other than the first position?
In fact this is what I really want to do:
newname = 'aasw_43w-f45_rmg-rk_dwfewf_rgrg_v-b';
nich = strfind(newname,''_'');
% find the position of last second '_':
positionLast2nd = nich(length(strfind(newname,''_''))-1)
=====
I tried to combine these two commands in one line as:
positionLast2nd = strfind(newname,''_'')(length(strfind(newname,''_''))-1)
error appears.
Stephen23
Stephen23 2017년 3월 3일
+1 nice use of regexp.

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


raym
raym 2017년 3월 3일
편집: Walter Roberson 2017년 3월 3일
newname = 'aasw_43w-f45_rmg-rk_dwfewf_rgrg_v-b';
eval('nich = strfind(newname,''_''); nich(length(strfind(newname,''_''))-1)')
% ans then could be used directly.
  댓글 수: 1
Walter Roberson
Walter Roberson 2017년 3월 3일
We distinctly recommend against using eval. eval() often leads to subtle bugs that show up only sometimes and are hard to find. It is also a big security risk.

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

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by