Use of 'regexp' (or equivalent) as conditional statement

조회 수: 8 (최근 30일)
Matthew
Matthew 2019년 3월 11일
댓글: Adam Danz 2019년 3월 11일
Hello,
I want to be able to tell Matlab that if a string ends with a (hyphen)-(word)-(number) pattern it should apply a certain rule, elsewise if a string ends with a (word)-(number)-(number) pattern to apply a different rule.
For example I need to be able to tell matlab to differentiate between:
  1. '- car 6'
  2. 'car 5 32'
(note that there is whitespace in there and the numbers can be between 1 and 4 figures)
Pseudocode for this is as follows:
if <string ends with (hyphen)-(word)-(number) pattern>
%do this
else <string ends with (word)-(number)-(number) pattern>
%do something else
I am fairly certain I can use the 'regexp' command to identify this, but I'm not certain of the syntax. Any help is appreciated.
Thanks,
Matt

채택된 답변

Adam Danz
Adam Danz 2019년 3월 11일
편집: Adam Danz 2019년 3월 11일
Here are the regular expressions that match your description. I'm using regexpi() which is not case sensitive. If you want case sensitivity, use regexp() instead with the same inputs. The expresssions are wrapped in isempty() and negated so each line will return a 1 if the expression is satisfied and a 0 if it is not satisfied.
The first one 'endsWithHiphenWordNum' returns TRUE if the input ends with [hyphen, word, number] with any amount of space between each. If you'd like to limit it to only 1 space between each, you can replace the "\s+" with a single space " " (without the quotes). The second one 'endsWithWordNumNum' returns TRUE if the input ends with [word, number, number] with any amount of space between each. Lastly, both expressions end with "$" which means that the input string is considered a match only if the expression is at the very end of the string.
a = 'example 1 is - car 6';
b = 'example 2 car 5 32';
endsWithHiphenWordNum = ~isempty(regexpi(a, '-\s+[a-z]+\s+\d+$')) % - aaa 11
endsWithWordNumNum = ~isempty(regexpi(b, '[a-z]+\s+\d+\s+\d+$')) % aaa 11 11
if endsWithHiphenWordNum
% do this
elseif endsWithWordNumNum
% do this
end
  댓글 수: 2
Matthew
Matthew 2019년 3월 11일
Thanks Adam! Your suggestion worked well for me.
Adam Danz
Adam Danz 2019년 3월 11일
Great! (my edit just fixed a couple typos).

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by