Use of 'regexp' (or equivalent) as conditional statement
6 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Adam Danz
on 11 Mar 2019
Edited: Adam Danz
on 11 Mar 2019
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 Comments
More Answers (0)
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!