From: Nicholas Heung on
Hi,

Using perl, I'm able to detect if a regex matches by doing an if statement - is this possible in MatLab, or would I just need to check if the results are empty?

Thanks
From: Walter Roberson on
Nicholas Heung wrote:

> Using perl, I'm able to detect if a regex matches by doing an if
> statement - is this possible in MatLab, or would I just need to check if
> the results are empty?

It depends which options you gave to regex about what it should return.

An "if" statement will succeed if all of the values are non-zero. For
example,

if [3 5 9]; disp('this will be displayed'); end
if [3 0 9]; disp('this will not be displayed'); end
if []; disp('this will not be displayed either'); end
if {}; disp('sorry this is invalid'); end

Thus if you set regex to return the vector of start indices, you could
code as

if regex(String,Pattern,'start')

and that would succeed if something matches.


On the other hand, it is much clearer programming to explicitly indicate
that you are testing a vector instead of the usual scalar

if all(regex(String,Pattern,'start'))

and in this particular case that would be equivalent to

if ~isempty(regex(String,Pattern,'start'))

Thus although you do not _need_ to test with isempty(), it is much more
readable if you do.


Note though that in perl, the match operator has side effects, setting
$1 and so on. Matlab's regexp does not have those side effects, so the
typical perl writing style becomes less common in Matlab.
From: Nicholas on
Thanks, that was very helpful.

Walter Roberson <roberson(a)hushmail.com> wrote in message <9Jh2o.47010$Ls1.30212(a)newsfe11.iad>...
> Nicholas Heung wrote:
>
> > Using perl, I'm able to detect if a regex matches by doing an if
> > statement - is this possible in MatLab, or would I just need to check if
> > the results are empty?
>
> It depends which options you gave to regex about what it should return.
>
> An "if" statement will succeed if all of the values are non-zero. For
> example,
>
> if [3 5 9]; disp('this will be displayed'); end
> if [3 0 9]; disp('this will not be displayed'); end
> if []; disp('this will not be displayed either'); end
> if {}; disp('sorry this is invalid'); end
>
> Thus if you set regex to return the vector of start indices, you could
> code as
>
> if regex(String,Pattern,'start')
>
> and that would succeed if something matches.
>
>
> On the other hand, it is much clearer programming to explicitly indicate
> that you are testing a vector instead of the usual scalar
>
> if all(regex(String,Pattern,'start'))
>
> and in this particular case that would be equivalent to
>
> if ~isempty(regex(String,Pattern,'start'))
>
> Thus although you do not _need_ to test with isempty(), it is much more
> readable if you do.
>
>
> Note though that in perl, the match operator has side effects, setting
> $1 and so on. Matlab's regexp does not have those side effects, so the
> typical perl writing style becomes less common in Matlab.