If Regexp matches return 1 otherwise 0 syntax

40 views (last 30 days)
Michael on 25 Mar 2013
Answered: gwoo on 23 Aug 2021
Right now I'm using the following to get a boolean result from a regexp. It just doesn't feel right - is there a better way to do this?

Accepted Answer

Walter Roberson
Walter Roberson on 25 Mar 2013
if regexp(myInput,myPattern)
regexp() by default returns a list of indices upon a match, and [] if there are no matches. The list of indices will all be non-zero numbers, and "if" applied to an array of non-zero numbers is considered to be true, just as if all() had been applied to the list. "if" applied to the empty matrix is false. So, you do not need to do any conversion: you can just test regexp() result directly.

Sign in to comment.

More Answers (3)

gwoo on 23 Aug 2021
This is how I get a logical array out of regex:
logicalMatches = ~cellfun('isempty', regexpi({filesInDir.name}, stringToBeFound, 'once'));


Community Treasure Hunt

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

Start Hunting!