【每日一题】我终于找到了适合自己的解决方案

我终于找到了适合自己的解决方案。

List part_one_CastTypeList = new List
{"void", "void "};
List part_two_CastTypeList = new List
{"void * ", "UBYTE", "VOID*", "const VOID*", "uint8", "void *"};
if ((Path.GetExtension(sourceFile) == ".cpp"))
{
    foreach (string e in part_one_CastTypeList)
    {
        string castType = null;
        foreach (char c in e)
        {
            castType = castType + '[' + c + ']';
        }
        // Match multi pattern, variant is inside function (Applicable for void type)
        // i.e (void)memcpy((FLOAT)a, (void *) b, (uint8)c)
        // ==> static_castmemcpy((FLOAT)a, (void *) b, (uint8)c)
        File.WriteAllText(sourceFile, Regex.Replace(
            File.ReadAllText(sourceFile),
            @"(" + castType + @")([^;rn}]*)();)",
            "static_cast($1)$2"));
    }
    foreach (string e in part_two_CastTypeList)
    {
        string castType = null;
        foreach(char c in e)
        {
            castType = castType + '[' + c + ']';
        }
        // Match single pattern, variant is not inside function (Not applicable for void type)
        // i.e (uint8)0x00,(uint16)0x01, (SW) 0x02
        // ==> static_cast(0x00),static_cast(0x01), static_cast(0x02),
        File.WriteAllText(sourceFile, Regex.Replace(
            File.ReadAllText(sourceFile),
            @"(" + castType + @")([^:/;)rn},]*)",
            "static_cast($1)"));
    }
}

我会将正则表达式分成两部分。第 1 部分(第一个 for 循环)将匹配函数的类型转换。第一个 for 循环完成后,函数的所有转换类型都应替换如下

static_cast(memcpy(&a[0],(void * )hihi, (UBYTE) V_SIZE));
static_cast( memcpy((VOID*)abc, (const VOID*) dafa, (uint8)NUMBER_SIZE));
static_cast(memcpy(
        (void *)p,
        &abc, (uint8)DATE_SIZE));

第 2 部分(第二个 for 循环)将匹配变体的类型转换并替换所有其余部分,如下所示

static_cast(memcpy(&a[0],static_cast(hihi), static_cast( V_SIZE)));
static_cast( memcpy(static_cast(abc), static_cast( dafa), static_cast(NUMBER_SIZE)));
static_cast(memcpy(
        static_cast(p),
        &abc, static_cast(DATE_SIZE)));

这不是 100% 完美,但我尝试了许多源文件,看起来不错,可以匹配高达 99% :))

© 版权声明
THE END
喜欢就支持一下吧
点赞237 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片