Use of 'regexp' (or equivalent) as conditional statement
7 ビュー (過去 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!