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

7 ビュー (過去 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 Center および File ExchangeCharacters and Strings についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by