关键代码
cpp
QStringList newLines;
for (const auto& line : lines) {
auto equalIndex = line.indexOf("=");
if(-1 != equalIndex) {
// a = b; 赋值
auto var = line.mid(0, equalIndex).trimmed();
auto value = line.mid(equalIndex + 1).trimmed();
if(value.endsWith(");")) { // a = b.get(); 赋值
value.replace("get", "set");
value.insert(value.size() - 2, var);
} else if(value.endsWith(";")) {
value.chop(1);
value += " = " + var;
}
newLines << value;
} else {
auto paramStartIndex = line.indexOf('(');
auto paramEndIndex = line.lastIndexOf(')');
if(-1 == paramStartIndex || -1 == paramEndIndex)
continue;
// 创建正则表达式 a->set(b.c.d);
QString pattern = R"(\w+(\.|->)set\w+\((\w+\.*)+\);)";
QRegularExpression regex(pattern);
QRegularExpressionMatch matchor = regex.match(line);
if (matchor.hasMatch()) {
// 获取匹配的内容
auto text = matchor.capturedTexts();
text << matchor.captured(0); // line
text << matchor.captured(1); // obj
text << matchor.captured(2); // func
text << matchor.captured(3); // param
auto var_name = line.mid(0, paramStartIndex);
var_name.replace("set", "get");
var_name += "()";
auto param_name = line.mid(paramStartIndex + 1, paramEndIndex - paramStartIndex - 1);
param_name += " = " + var_name + ";";
newLines << param_name;
}
// b->get() (\\w+)(->|\\.)\\w+(\\(|$)
// 创建正则表达式 a->set(b.get());
pattern = R"(\w+(->|\.)set\w+\(((\w+)(->|\.))*get\w+\(\)\);)";
regex.setPattern(pattern);
// 查找匹配项
matchor = regex.match(line);
if (matchor.hasMatch()) {
// 获取匹配的内容
QString matchedText = matchor.captured(0);
QString objectName = matchor.captured(1);
QString functionName = matchor.captured(2);
QString parameterFunctionCall = matchor.captured(3);
auto var_name = line.mid(0, paramStartIndex);
var_name.replace("set", "get");
var_name += "()";
auto param_name = line.mid(paramStartIndex + 1, paramEndIndex - paramStartIndex - 1);
param_name.replace("get", "set");
param_name.insert(param_name.size() - 1, var_name);
param_name += ';';
newLines << param_name;
}
}
}