Home > Software design >  matlab regular expression to check if variables are set in a script
matlab regular expression to check if variables are set in a script

Time:09-16

To check if one or more variables (like var1, var2, ...) are set in the script, I read the script into a list of strings (line by line) and check if a line looks like

var1=...
[var1,x]=...
[var2,x]=...
[x,y,var1,z]=...

Currently I'm use the following pattern

pattern = '^([.*)?(var1|var2|var3)(.*])?=';
ix = regexp(s,pattern,'once');

It works for my purpose but I know it's not a safe pattern, because something like [x,vvvar1,y]=... also matches the pattern.

My current solution is to make separate patterns for each type of expressions, but I wonder if there is a unique pattern that can meet my needs.


Here are some examples, if I want to match any of abc or def,

pattern = '^([.*)?(abc|def)(.*])?=';

%% good examples
regexp('x=1',pattern,'once') % output []
regexp('aabc=1',pattern,'once') % output []
regexp('abc=1',pattern,'once') % output 1
regexp('[other,abc]=deal(1,2)',pattern,'once') % output 1

%% bad examples
regexp('[x,aabcc]=deal(1,2)',pattern,'once') % output 1
regexp('[x,abcc,y]=deal(1,2,3)',pattern,'once') % output 1

CodePudding user response:

You want to make sure there is at least one specific variable in the string.

You can use

^\[?(\w ,)*(abc|def)(,\w )*]?=

See the regex demo.

Details:

  • ^ - start of string
  • \[? - an optional literal [ char
  • (\w ,)* - zero or more one or more word chars a comma sequences
  • (abc|def) - either abc or def
  • (,\w )* - zero or more comma one or more word chars sequences
  • ]? - an optional ] char
  • = - a = char.
  • Related