If Regexp matches return 1 otherwise 0 syntax

조회 수: 68 (최근 30일)
Michael
Michael 2013년 3월 25일
편집: gwoo 2023년 2월 8일
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)

채택된 답변

Walter Roberson
Walter Roberson 2013년 3월 25일
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.
  댓글 수: 3
Walter Roberson
Walter Roberson 2013년 3월 25일
편집: Walter Roberson 2013년 3월 25일
~isempty(regexp('aa00aa00', '\d+')) && 1
or
any(regexp('aa00aa00', '\d+')) && 1
Note: all() instead of any() will not work.
Michael
Michael 2013년 3월 25일
Thanks

댓글을 달려면 로그인하십시오.

추가 답변 (3개)

gwoo
gwoo 2021년 8월 23일
편집: gwoo 2023년 2월 8일
If your input to regex is a cell array (say from collecting from a struct or something), then your output will be a cell array which is not immediately able to be used for logical indexing. You need to convert it from a cell array to a logical array. But many times you'll get empty cells so you can't just use cell2mat because that will implicitly ditch the empty cells and only leave you with the non-empty which doesn't help for indexing. Therefore, I use this following approach to go from an input of a cell array to an output of a logical array.
This is how I get a logical array out of regex:
logicalMatches = ~cellfun('isempty', regexpi({filesInDir.name}, stringToBeFound, 'once'));
  댓글 수: 1
James Van Zandt
James Van Zandt 2022년 5월 12일
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

댓글을 달려면 로그인하십시오.


Sean de Wolski
Sean de Wolski 2013년 3월 25일
doc strfind %?

Azzi Abdelmalek
Azzi Abdelmalek 2013년 3월 25일
Maybe you want to use isequal or strcmp

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by