matlab正则表达式检查脚本中是否设置了变量

matlab regular expression to check if variables are set in a script

为了检查脚本中是否设置了一个或多个变量(如 var1, var2, ...),我将脚本读入字符串列表(逐行)并检查一行是否看起来像

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

目前我正在使用以下模式

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

它适用于我的目的,但我知道这不是一个安全的模式,因为 [x,vvvar1,y]=... 之类的东西也匹配该模式。

我目前的解决方案是为每种类型的表达式制作单独的模式,但我想知道是否有一种独特的模式可以满足我的需求。


这里有一些例子,如果我想匹配abcdef

中的任何一个
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

您想确保字符串中至少有一个特定变量。

您可以使用

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

参见regex demo

详情:

  • ^ - 字符串开头
  • \[? - 可选文字 [ char
  • (\w+,)* - 零个或多个一个或多个单词字符 + 逗号序列
  • (abc|def) - abcdef
  • (,\w+)* - 零个或多个逗号 + 一个或多个单词字符序列
  • ]? - 一个可选的 ] 字符
  • = - 一个 = 字符。