regex - Matlab 正则表达式 ${numberFun($4)} - 'char' 类型的输入参数的未定义函数 'numberFun'
问题描述
我在 Matlab 中读到,可以在这样的正则表达式转换中包含函数调用$1double$2[${doubleTextNumber($4)}]
,假设 1、2、3 是一些正则表达式组,而 4 是纯数字组。我想要做的确切的事情是捕获所有由类型 creal_T 组成的数组,将类型替换为 double 并将数组的长度加倍。
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+)\])',
"$1double$2[${doubleTextNumber($4)}]");
然而,当我运行这段代码时,Matlab 给了我以下错误消息:
Error using regexprep
Evaluation of 'doubleTextNumber($4)' failed:
Undefined function 'doubleTextNumber' for input arguments of type 'char'.
据我了解,我已经使该方法从 char 进行转换,并希望它也能从我的正则表达式中接受这个值。我已经测试过当我直接输入“704”或“704”时它可以工作,并且正则表达式也可以从这个插入中工作。
为什么 Matlab 找不到我的正则表达式中的函数?(它们在同一个 m 文件中)
解决方案
看起来我原来的方法有 3 个问题:
为了
regexprep()
识别我的函数,它必须被移动到它自己的 m 文件中。简单地从同一个文件中调用一个方法是行不通的。我使用https://regex101.com/来编辑搜索表达式,但即使它似乎选择了括号内的数字,第 4 组也没有
regexprep()
在 Matlab 中填充。一个新版本确实有效,并用我想要的数字填充了第 3 组:(?m)^(\W*)creal_T(\s*\w*).([^\]]*\d*)\]
我还在乘法方法中添加了更多转换选项,以防输入是数字和字符数组的组合。
我的正则表达式调用的最终版本变为:
resultString = regexprep(
codeText,
'(?m)^(\W*)creal_T(\s*\w*).([^\]]*\d*)\]',
"$1double$2[${multiplyTextNumbers($3,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
希望这对面临类似问题的其他人有所帮助。
推荐阅读
- elasticsearch - 桶太多,直方图聚合失败
- pdf - 为什么从同一个安全 PDF 中删除安全性后 MD5 校验和会发生变化?
- android - 没有收到 Firebase 通知
- c# - .NET Core/MVC - 查看将空模型发布回控制器
- php - 将颜色选择器添加到插件以更改内容的文本颜色
- database - 如何连接一个数据库与多个窗口应用程序?
- php - 使用自定义 (ACF) 字段创建自定义查询以在 Wordpress 中显示关系数据
- c# - 在 linq 到 sql 连接上出现错误“不支持此服务器版本。只有最高 microsoft sql server 2005 的服务器”?
- android - 使用 Retrofit 解析 JSON
- c++ - 如何在 c++ 中使用 x 和 y 值找到圆和矩形的计算几何?