If Regexp matches return 1 otherwise 0 syntax

83 views (last 30 days)
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)

Sean de Wolski
Sean de Wolski on 25 Mar 2013
doc strfind %?

gwoo on 23 Aug 2021
This is how I get a logical array out of regex:
logicalMatches = ~cellfun('isempty', regexpi({filesInDir.name}, stringToBeFound, 'once'));
  1 Comment
James Van Zandt
James Van Zandt on 12 May 2022
I have a cell array of strings to test, so I used this method to collect the matches.
K>> ca={'able','baker','charlie','delta','echo','fox','golf','hotel'}
ca =
1×8 cell array
{'able'} {'baker'} {'charlie'} {'delta'} {'echo'} {'fox'} {'golf'} {'hotel'}
K>> regexp(ca,'a')
ans =
1×8 cell array
{[1]} {[2]} {[3]} {[5]} {0×0 double} {0×0 double} {0×0 double} {0×0 double}
K>> ~cellfun('isempty',regexp(ca,'a'))
ans =
1×8 logical array
1 1 1 1 0 0 0 0

Sign in to comment.

Azzi Abdelmalek
Azzi Abdelmalek on 25 Mar 2013
Maybe you want to use isequal or strcmp


Find more on Variables 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!