If Regexp matches return 1 otherwise 0 syntax
78 views (last 30 days)
Show older comments
Hi,
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?
(size(regexp(myInput,myPattern),1)>0)
Accepted Answer
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.
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'));
1 Comment
James Van Zandt
on 12 May 2022 at 19:40
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
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!