Use of 'regexp' (or equivalent) as conditional statement
조회 수: 8 (최근 30일)
이전 댓글 표시
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:
- '- car 6'
- '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
댓글 수: 0
채택된 답변
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!