Matlab 正则表达式 ${numberFun($4)} - 类型为 'char' 的输入参数的未定义函数 'numberFun'

Matlab regex ${numberFun($4)} - Undefined function 'numberFun' for input arguments of type 'char'

我读到在 Matlab 中可以像这样在正则表达式转换中包含函数调用 double[${doubleTextNumber()}],假设 1、2、3 是一些正则表达式组,4 是纯数字组.我想要做的确切事情是捕获所有由 creal_T 类型组成的数组,用双倍的类型替换数组的长度。

codeText = "typedef struct {
      double tolRob;
      creal_T Mt2o[704];
      creal_T Ho2o[704];
      creal_T Ht2t[704];
      creal_T Zo2t[704];
      creal_T Ztd[64];
 } testType;"

所以,我希望上面的结构变成:

typedef struct {
      double tolRob;
      double Mt2o[1408];
      double Ho2o[1408];
      double Ht2t[1408];
      double Zo2t[1408];
      double Ztd[128];
 } SpdEstType;

在 Matlab 中我做了一个函数将数字转换为文本并将其加倍:

function [doubleValue] = doubleTextNumber(inputNumber)
    doubleValue =  string(str2double(inputNumber)*2.0);
end

我还有一个正则表达式,我希望它能在每个声明中找到数字并将其提供给函数:

resultString = regexprep(
codeText,
'(?m)^(\W*)creal_T(\s*\w*)(\[([^\]]*\d+)\])',
"double[${doubleTextNumber()}]");

然而,当我 运行 这段和平代码时,Matlab 给了我以下错误消息:

Error using regexprep
Evaluation of 'doubleTextNumber()' failed:

Undefined function 'doubleTextNumber' for input arguments of type 'char'.

据我所知,我已经使该方法从 char 进行转换,并希望它也能从我的正则表达式中接受这个值。我已经测试过当我直接输入“704”或“704”时它可以工作,并且正则表达式从这个插入中可以正常工作。

为什么 Matlab 不能从我的正则表达式中找到函数? (他们在同一个m文件中)

看来我原来的方法有 3 个问题:

  1. 为了 regexprep() 识别我的函数,必须将它移动到它自己的 m 文件中。简单地从同一个文件中调用一个方法是行不通的。

  2. 我正在使用 https://regex101.com/ 编辑搜索表达式,但即使它似乎选择了括号内的数字,第 4 组也没有被 regexprep() 填充在Matlab中。一个新版本确实有效,并用我想要的数字填充了第 3 组:(?m)^(\W*)creal_T(\s*\w*).([^\]]*\d*)\]

  3. 我还为我的乘法方法添加了更多转换选项,以防输入是数字和字符数组的组合。

我的正则表达式调用的最终版本变为:

resultString = regexprep(
    codeText,
    '(?m)^(\W*)creal_T(\s*\w*).([^\]]*\d*)\]',
    "double[${multiplyTextNumbers(,2)}]");

其中 multiplyTextNumbers() 在其自己的 m 文件中定义为

function [productText] = multiplyTextNumbers(inputFactorText1,inputFactorText2)
%MULTIPLY This method takes numbers as input, and acepts either string,
%char or double or any combination of the three. Returns a string with the
%resulting product. 
    if (isstring(inputFactorText1) || ischar(inputFactorText1))
        inputFactor1 = str2double(inputFactorText1);
    else
        inputFactor1 = inputFactorText1;
    end

    if (isstring(inputFactorText2) || ischar(inputFactorText2))
        inputFactor2 = str2double(inputFactorText2);
    else
        inputFactor2 = inputFactorText2;
    end

    productText =  sprintf('%d',inputFactor1*inputFactor2);
end

希望这对面临类似问题的其他人有所帮助。