Code covered by the BSD License  

Highlights from
What's New In MATLAB 7.2 R2006a

image thumbnail

What's New In MATLAB 7.2 R2006a

by

Jeremy Barry (view profile)

 

07 Mar 2006 (Updated )

Webinar presentation and demo files

newregexp_short.m
%% Dynamic creation of a search string 
strs={'3XXX', '12XXXXXXXXXXXX' '5XXXXX'};

%%
match=regexp(strs, '^(\d+)(??X{$1})$', 'match', 'once')

%% Dynamic creation of a search string with M code
str = 'Never odd or even'; 

%%
s1=regexprep(str, '(\w*)(\W*)', '${lower($1)}'); 

%%
match=regexp(s1, '^(.*).?(??@fliplr($1))$') 

%% Dynamic creation of a replacement string with M code
str = 'Will this work?'; % Test string
var = genvarname(str) % Convert to legal variable name (chars to 0xhex number)

%%
% *How it was done in the past*
found = regexp(var, '0x([0-9A-F]{2})', 'match', 'once');

while ~isempty(found) % Repeat until all replaced
    hex = found(3:4); % Find codes
    ch = char(hex2dec(hex)); % Convert back to single char
    var = strrep(var, found, ch); % Replace code with single char
    found = regexp(var, '0x([0-9A-F]{2})', 'match', 'once'); % Find again
end 

var

%%
% *Now its much easier*
var = genvarname(str)
%%
% "match" represents the whole ending to be replaced while "token" is
% represented with $1
[token match]=regexp(var, '0x([0-9A-F]{2})','tokens','match');
token{1}
match
%% 
% Putting it all together
match=regexprep(var, '0x([0-9A-F]{2})', '${char(hex2dec($1))}')

%% Dynamic recursive matching with M code
str='asdf(ASDF(ASD)ASDF(ASDF(ASDF)ASDF)ASDF)asdf';

%%
levelN = '\(([^()]|(??@levelN))*\)'; % This says match either a parethesis or the levelN expression
match=regexp(str, levelN, 'match', 'once')

%% Matching modes
str = ['this is the first line' 10 'this is the second line']

%%
% For example,
match=regexp(str, '.*', 'match')

%%
match=regexp(str, '.*', 'match', 'dotexceptnewline');
match{1}
match{2}

%% Warnings
s = regexp('a(b[c)d]e','a(b','warnings')

%%
s = regexp('a(b[c)d]e','a\(b','warnings')

Contact us